How to Convert Nested Arrays Into 1d Array in Javascript

Thursday, April 22, 2021 • One minute to read


In ES2019, Array.prototype.flat method was introduced which converts the multi-dimensional array to one-dimensional array upto a defined nested depth.

For Example:

1const nestedArr = ["e1", ["e2", "e3", ["e4", "e5", ["e6", "e7"]]]];
2// default depth is 1 means it will flated only 1 nested array
3nestedArr.flat(); // ["e1", "e2", "e3", ["e4", "e5", ["e6", "e7"]]]
5// depth = 2
6nestedArr.flat(2); // ["e1", "e2", "e3", "e4", "e5", ["e6", "e7"]]
8// for all the way down to the last nested array use Infinity
9nestedArr.flat(Infinity); // ["e1", "e2", "e3", "e4", "e5", "e6", "e7"]

The flat method is not supported on old version of many browsers.

Checkout supported versions here.


PreviousHow to Add RSS feed to Hugo Website

NextHow to Remove Falsy Values From an Array in Javascript