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);
result
is then an array with each item from arr
multiplied by two.
[2, 4, 6]
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]);
In this case, our result is this.
[[1, 2],[2, 4],[3, 6]]
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]
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]
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] ]
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.