DEV Community

Rajika Imal
Rajika Imal

Posted on

JavaScript Array.flat()

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

Top comments (2)

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.