DEV Community

Mohd Ahshan Danish
Mohd Ahshan Danish

Posted on

flatMap vs map in Array

flatMap: It is identical to a map() followed by a flat() of depth 1 (arr.map(...args).flat()), but slightly more efficient than calling those two methods separately.

let LIST = [1,2,3];
let processedLst = LIST.flatMap((route) => {
    return [route, route];
  }).filter(Boolean);
console.log(processedLst)
// [ 1, 1, 2, 2, 3, 3 ]
Enter fullscreen mode Exit fullscreen mode

map:

let LIST = [1,2,3];
let processedLst = LIST.map((route) => {
    return [route, route];
  }).filter(Boolean);
console.log(processedLst)
//[ [ 1, 1 ], [ 2, 2 ], [ 3, 3 ] ]
Enter fullscreen mode Exit fullscreen mode

flat():

processedLst.flat()
//[ 1, 1, 2, 2, 3, 3 ]
Enter fullscreen mode Exit fullscreen mode

I will be posting tricks I have been using in my journey.
So follow me on LinkedIn.

Top comments (0)