DEV Community

Djilou
Djilou

Posted on

A useful array method in Javascript

Have you faced a nested array before? With nested i mean this for example:
const array=[1,2,3,[4,5]]
If we want to access to all of it's elements one by one we will have to use nested map methods too, so to avoid that we can use the flat method

array.flat()
Which will return an array

[1,2,3,4,5]
This is all good and fun but if our main goal was to map across all of the items we still have to use map,so why don't we combine both methods in a single one?
array.flatMap((item)=>console.log(item))
Will do the job.

That's it,happy coding.
Ps:try these methods with this array
const nastyNested=[1,2,3,4,[[5,6]]]

Top comments (0)