Flatten an array in javascript

Learn how to convert a multi-dimensional array into single dimension array in javascript

Flattening the array in Javascrip

We can flatten an array to single dimension array using Array.flat(depth) method.

But if we have multi-dimensional array then we need to find the depth of the Array, instead of finding depth we can solve the problem in two ways

we can pass Infinity as depth ,


Input : [1,2,3, [2,3,[1,2,[3,4]],4,5,6]];

Expected Output : [1,2,3,2,3,1,2,3,4,4,5,6]

Consider we have input and result array .

We can loop through each element in input array,

If

  • current element is not an array then push the element into the result array,
  • current element is an array then again loop through all the elements of the current element , if we have another array then call the same function recursively .


There is another simple way to do the same using the string split method,
var a = [1,2,3, [1,2, [1,2, [1,2] ] ] ];
a = a + ""; // results in --> 1,2,3,1,2,1,2,1,2
a = a.split(',');  // ["1", "2", "3", "1", "2", "1", "2", "1", "2"]

But all the elements are converted to string , if it is not a problem then we can use this method.

If you find this helpful surprise 🎁 me here.

Share if you feel happy.

Follow Javascript Jeep🚙 if you feel worthy.

Leave a comment

Design a site like this with WordPress.com
Get started