How to Convert Nested Arrays Into 1d Array in Javascript

Thursday, April 22, 2021 • One minute to read

Javascript2021to-the-pointjavscriptto-the-point2021

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"]]]
4
5// depth = 2
6nestedArr.flat(2); // ["e1", "e2", "e3", "e4", "e5", ["e6", "e7"]]
7
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.


Javascript2021to-the-pointjavscriptto-the-point2021

PreviousHow to Add RSS feed to Hugo Website

NextHow to Remove Falsy Values From an Array in Javascript