Flatten or Merge nested array in JavaScript

There may be a requirement to merge or flatten the array of array for better representation or readability. There are various ways to achieve this in javascript. We will try all possible ways to achieve the same.

This is our sample set:

let nested_array = [[1,2,3],23,['a','e'],34,[5,6,7]]

1. concat

[].concat(...nested_array)
// [1, 2, 3, 23, 'a', 'e', 34, 5, 6, 7]

2. Using Flat method

nested_array.flat()
// [1, 2, 3, 23, 'a', 'e', 34, 5, 6, 7]

The above method can help merge nested arrays up to 1 levels. For more than two-level we can use flat() a different way.

3. For infinite nested array

3.1 flat(depth)

nested_array = [[1,2,3],23,['a','e'],34,[5,6,7], [['L3']], [[['L4']]]]
nested_array.flat(Infinity)
// [1, 2, 3, 23, 'a', 'e', 34, 5, 6, 7, 'L3', 'L4']

You can read about flat() Here

3.2 reduce + concat + isArray + recursivity

function flatDeep(arr, d = 1) {
   return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
 : arr.slice();
};
flatDeep(nessted_array)
// [1, 2, 3, 23, 'a', 'e', 34, 5, 6, 7, 'L3', 'L4']

Leave a Reply