Understanding Array.prototype.flatMap

Laurie - Jun 25 '19 - - Dev Community

Last week we talked about the new flat method available in ES2019.

This week, we're going to dive into flatMap!

Let's start with map

In JavaScript arrays a have a built-in function called map. It takes a function and uses that function to operate on each item in the array. Something like this.

let arr = [1, 2, 3]

let result = arr.map((item) => item * 2);
Enter fullscreen mode Exit fullscreen mode

result is then an array with each item from arr multiplied by two.

[2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Another way to work with map

You can also use map to create a data structure inside each array element! Let's look at this example.

let arr = [1, 2, 3]

let result = arr.map((item) => [item, item * 2]);
Enter fullscreen mode Exit fullscreen mode

In this case, our result is this.

[[1, 2],[2, 4],[3, 6]]
Enter fullscreen mode Exit fullscreen mode

It's common to want to flatten this.

So you have

let arr = [1, 2, 3]

let result = arr.map((item) => [item, item * 2]).flat();

[1, 2, 2, 4, 3, 6]
Enter fullscreen mode Exit fullscreen mode

But not with flatMap!

With the addition of flatMap this becomes simpler!

let arr = [1, 2, 3]

let result = arr.flatMap((item) => [item, item * 2]);

[1, 2, 2, 4, 3, 6]
Enter fullscreen mode Exit fullscreen mode

It's the same thing.

Important

The default argument for flat is 1, NOT Infinity. This is important because flatMap is the same way. Let's look at an example.

let arr = [1, 2, 3]

let result = arr.flatMap((item) => [item, [item]]);

[ 1, [1], 2, [2], 3, [3] ]
Enter fullscreen mode Exit fullscreen mode

The array is not fully flattened because flatMap only flattens one level.

Conclusion

flatMap is a great built-in function for this popular pattern! Check it out and let me know what you think.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .