This page looks best with JavaScript enabled

Flatten recursive arrays

 ·   ·  ☕ 1 min read

Flatten recursive arrays using Array.flat().

We have seen how to flatten arrays before. Array.flat() is quite useful to flatten arrays in one statement and output a simpler array.

But, what about situations where you do not know the depth of array hierarchy -

1
const nums = [[1, 2], [3, 4], [[5], [6]], [[[7]]]];

Fear not. Array.flat() takes in an argument to flatten to a specific depth or flatten everything.

1
2
3
4
5
6
7
8
console.log(nums.flat());
// [ 1, 2, 3, 4, [ 5 ], [ 6 ], [ [ 7 ] ] ]

console.log(nums.flat(2));
// [1, 2, 3, 4, 5, 6, [7]];

console.log(nums.flat(Infinity));
// [ 1, 2, 3, 4, 5, 6, 7 ]
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things