JavaScript – Flatten an Array

There are several ways to flatten an array in JavaScript. Let’s explore some of the ways to flatten an array.

Using the flat() method

The flat() method creates a new array with all array elements added consecutively to the desired depth. The depth parameter is optional. 1 is considered the default depth.

const arr = [1, [2, [3, [4]], 5]];

// Default flatten (depth 1)
console.log(arr.flat()); // [1, 2, [3, [4]], 5]

// Flatten to infinite depth
console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5]

// Flatten to depth 2
console.log(arr.flat(2)); // [1, 2, 3, [4], 5]

Using the reduce method with recursion

const arr = [1, [2, [3, [4]], 5]];

const flatten = (array) =>
  array.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []);

console.log(flatten(arr)); // [1, 2, 3, 4, 5]

Using concat() and apply()

This method uses concat() combined with apply() to flatten an array by one level.

const arr = [1, [2, [3, [4]], 5]];
const flattened = [].concat.apply([], arr);
console.log(flattened); // [1, 2, [3, [4]], 5]

Using spread operator

The Spread operator can also flatten the array to one level.

const arr = [1, [2, [3, [4]], 5]];
let flatArray = [].concat(...arr);
console.log(flatArray); // [1, 2, [3, [4]], 5]

Similar Reads