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 -
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.
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 ]