DEV Community

loading...

JavaScript Array.flat()

rajikaimal profile image Rajika Imal ・1 min read

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]
Enter fullscreen mode Exit fullscreen mode

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]]]
Enter fullscreen mode Exit fullscreen mode
const array = [1, 2, 3, 4, [[[5, 6]]]]
const flatArray = array.flat(3) // [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

pic
Editor guide
Collapse
sami_hd profile image
Sami

Everybody should know this

Collapse
patarapolw profile image
Pacharapol Withayasakpunt

It should throw errors if arrays cannot be flattened (but it doesn't).

Also can be reproduced with simply reduce.