How to deep flatten an array in JavaScript?


Flattening an array

Flattening an array is nothing but merging a group of nested arrays present inside a provided array. 

Flattening of an array can be done in two ways.

 1) concat.apply() 

In the following example there are some nested arrays containing elements 3,4,5 and 6. After flattening them using concat() method we get the output as 1,2,3,4,5,6,9.

 Example

 Live Demo

<html>
<body>
<script>
   var arrays = [1,2,[3,4,[5,6]],9];
   var merged = [].concat.apply([], arrays);
   documemt.write(merged);
</script>
</body>
</html>

Output

1,2,3,4,5,6,9


2) array.flat()

In the following example there are some nested elements such as 2,3,4,5,6,9. After Flattening them using array.flat() method we get the output as 1,2,2,3,4,5,6,9.

Example

 Live Demo

<html>
<body>
<script>
   const arrays = [1,2,[2,3,[4,5,[6,9]]]];
   const merged = arrays.flat(2);
   document.write(merged)
</script>
</body>
</html>

Output

1,2,2,3,4,5,6,9

Updated on: 30-Jul-2019

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements