title: Flattening multidimensional Arrays in JavaScript tip-number: 38 tip-username: loverajoel tip-username-profile: https://www.twitter.com/loverajoel tip-tldr: Three different solutions to merge multidimensional array into a single array. tip-writer-support: https://www.coinbase.com/loverajoel
- /en/flattening-multidimensional-arrays-in-javascript/
These are the three known ways to merge multidimensional array into a single array.
Given this array:
var myArray = [
[1, 2],
[3, 4, 5],
[6, 7, 8, 9]
];
We wanna have this result:
[1, 2, 3, 4, 5, 6, 7, 8, 9];
var myNewArray = [].concat.apply([], myArray);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Solution 2: Using reduce()
var myNewArray = myArray.reduce(function (prev, curr) {
return prev.concat(curr);
});
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
var myNewArray3 = [];
for (var i = 0; i < myArray.length; ++i) {
for (var j = 0; j < myArray[i].length; ++j) myNewArray3.push(myArray[i][j]);
}
console.log(myNewArray3);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Solution 4: Using spread operator in ES6
var myNewArray4 = [].concat(...myArray);
console.log(myNewArray4);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Solution 5: Using flat()
in ES10
var myNewArray5 = myArray.flat();
console.log(myNewArray5);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Take a look here these 4 algorithms in action.
For infinitely nested array try Lodash flattenDeep().
If you are curious about performance, here a test for check how it works.