javascript array flatten

Flattening an array in JavaScript is a process in which we take an array of arrays and transform it into a single array. This process is useful when we want to work with a single array instead of multiple arrays when dealing with data that requires processing or manipulation.

The flatten() method is a built-in method provided by the JavaScript language to flatten an array. This method takes in a single parameter which is the array that needs to be flattened and returns a single array which is the flattened result.


// example of an array of arrays
var arr = [[1,2,3], [4,5,6], [7,8,9]];

// flatten the array using the flatten() method
var flattenedArr = arr.flatten();

// output: [1,2,3,4,5,6,7,8,9]
console.log(flattenedArr);

Apart from the flatten() method, we can also use the reduce() method in JavaScript to flatten an array. The reduce() method takes in a callback function which will be called on each element of the array. We can use this callback to construct a new array with the flattened elements of the original array.


// example of an array of arrays
var arr = [[1,2,3], [4,5,6], [7,8,9]];

// flatten the array using the reduce() method
var flattenedArr = arr.reduce((acc, val) => acc.concat(val), []);

// output: [1,2,3,4,5,6,7,8,9]
console.log(flattenedArr);

We can also use the spread operator (...) to flatten an array. This approach is quite simple and easy to understand. All we have to do is to use the spread operator (...) to expand the elements of the array which is inside another array.


// example of an array of arrays
var arr = [[1,2,3], [4,5,6], [7,8,9]];

// flatten the array using the spread operator
var flattenedArr = [].concat(...arr);

// output: [1,2,3,4,5,6,7,8,9]
console.log(flattenedArr);

These are some of the ways that we can use to flatten an array in JavaScript. Hence, it is important to understand the pros and cons of each approach and use the approach that best suits our use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe