Understanding Array.prototype.flatMap

laurieontech

Laurie

Posted on June 25, 2019

Understanding Array.prototype.flatMap

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.

💖 💪 🙅 🚩
laurieontech
Laurie

Posted on June 25, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Introducing Object.fromEntries
javascript Introducing Object.fromEntries

July 2, 2019

Understanding Array.prototype.flatMap
javascript Understanding Array.prototype.flatMap

June 25, 2019

Demystifying Array.prototype.flat
javascript Demystifying Array.prototype.flat

June 18, 2019