Arrays with embedded sub arrays can be concatenated using Array.flat()
const array = [1, 2, 3, 4, [5, 6]]
const flatArray = array.flat() // [1, 2, 3, 4, 5, 6]
The depth can be specified using an argument. Array.flat(depth)
const array = [1, 2, 3, 4, [[[5, 6]]]]
const flatArray = array.flat(1) // [1, 2, 3, 4, [[5, 6]]]
const array = [1, 2, 3, 4, [[[5, 6]]]]
const flatArray = array.flat(3) // [1, 2, 3, 4, 5, 6]
Top comments (2)
Everybody should know this
It should throw errors if arrays cannot be flattened (but it doesn't).
Also can be reproduced with simply reduce.