ES6 | Flatten a multi-dimensional array
Several ways exist to flatten an array — In this article, I will present you 2 efficient techniques to do so with ES6.
Using the spread operator
You can use the ES6 spread operator to do so.
const multiDimensionalArray = [ [1, 2], [3, 4], [5, 6] ];
const flattenedArray = [].concat(…multiDimensionalArray);
console.log(flattenedArray) // [1, 2, 3, 4, 5, 6]
⚠️ Important note:
This way of flattening only works with an array depth of one.
Using Array.prototype.flat()
A method on array also exists that permits to flatten the array:
const multiDimensionalArray = [ [1, 2], [3, 4], [5, 6] ];
const flattenedArray =multiDimensionalArray.flat();
console.log(flattenedArray) // [1, 2, 3, 4, 5, 6]
This method accepts one argument to choose the depth of the flattening.
const multiDimensionalArray = [[ [1, 2]], [3, 4], [5, 6] ];
multiDimensionalArray.flat(2);
console.log(flattenedArray) // [1, 2, 3, 4, 5, 6]
⚠️ Important note:
If you don’t use a transpiler this method won’t work with Internet Explorer and Edge.
Also, you won’t be able to use it with Node.js versions prior to 11.0.0
🙏🏻 Thank you for reading.
If you have any comment, question or more efficient and powerful way to flatten arrays, feel free to comment on this article.