Smarter JavaScript mapper: array.flatMap()
Original: https://dmitripavlutin.com/javascript-array-flatmap/
array.map()
is a very useful mapper function: it takes an array and a mapper function, and returns a new array of maps.
However, there is an alternative array.map()
: ( array.flatMap()
available starting from ES2019). This method enables you to map and also remove or even add new items to the resulting map array.
1. Smarter mappers
Having an array of numbers, how would you create a new array with doubled items?
Using the array.map()
function is a good way:
const numbers = [0, 3, 6];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // logs [0, 6, 12]
numbers.map(number => 2 * number)
the array numbers
to a new array where each number is doubled.
For cases where a one-to-one mapping is required, meaning the mapped array will have the same number of items as the original array, array.map()
works well.
But what if you need to double the number of arrays and skip zeros from the map?
Using array.map()
directly is not possible because the method always creates a mapped array with the same number of items as the original array. But you can use array.map()
and a combination of array.filter()
:
const numbers = [0, 3, 6];
const doubled = numbers
.filter(n => n !== 0)
.map(n => n * 2);
console.log(doubled); // logs [6, 12]
doubled
array now contains numbers
times 2 entries, and also does not contain any zeros.
array.map()
combination array.filter()
map and filter array. But is there a shorter way?
Yes! Thanks to the array.flatMap()
method, you can perform mapping and delete items with just one method call.
Here's how to use array.flatMap()
to return a new mapped array with doubled items, while filtering for zeros 0
:
const numbers = [0, 3, 6];
const doubled = numbers.flatMap(number => {
return number === 0 ? [] : [2 * number];
});
console.log(doubled); // logs [6, 12]
By just using numbers.flatMap()
you can map one array to another, but also skip certain elements in the map.
Let's see in more detail how array.flatMap()
works.
2.array.flatMap ()
array.flatMap()
function accepts a callback function as an argument and returns a new array of maps:
const mappedArray = array.flatMap((item, index, origArray) => {
// ...
return [value1, value2, ..., valueN];
}[, thisArg]);
The callback function is called on each itam in the original array with 3 parameters: the current item, the index and the original array. The array returned by the callback is then flattened 1 level deep and the resulting item is added to the mapped array.
Additionally, the method accepts a second optional parameter indicating the value inside the this
The easiest way you can use array.flatMap()
is to flatten the array containing the items as an array:
const arrays = [[2, 4], [6]];
const flatten = arrays.flatMap(item => item);
console.log(flatten); // logs [2, 4, 6]
In the example above arrays
contains an array of numbers: [[2, 4], [6]]
. Call arrays.flatMap(item => item)
the array to [2, 4, 6]
.
But array.flatMap()
can do much more than simply flattening. By controlling the number of array items returned from the callback, you can:
- Remove item
[]
by returning an empty array - modify the map entry by returning an array with a new value
[newValue]
- Or by returning to an array having a plurality of values added
[newValue1, newValue2, ...]
new items:
For example, as you saw in the previous section, you can create a new array by doubling the items, but you can also remove zeros 0
:
const numbers = [0, 3, 6];
const doubled = numbers.flatMap(number => {
return number === 0 ? [] : [2 * number];
});
console.log(doubled); // logs [6, 12]
Let's see in more detail how the above example works.
[]
callback function returns an empty array 0
if the current item is 061df9cca65f0c. This means that when flattened, the empty array []
provides no value at all.
If the current iteration term is not zero, [2 * number]
returns. When the [2 * number]
array is flattened, only 2 * number
is added to the resulting array.
You can also use array.flatMap()
to increase the number of items in the mapped array.
For example, the following code snippet maps an array of numbers to a new array by adding double and triple numbers:
const numbers = [1, 4];
const trippled = numbers.flatMap(number => {
return [number, 2 * number, 3 * number];
});
console.log(trippled);
// logs [1, 2, 3, 4, 8, 12]
3. Conclusion
array.flatMap()
Method is the way to go if you want to map an array to a new array, but also controls how many items you want to add to the new mapped array.
The callback function of array.flatMap(callback)
with 3 arguments: the current iteration item, the index, and the original array. The array returned from the callback function is then flattened at level 1 depth and the resulting item is inserted into the resulting map array.
Note that if you just want to map a single item to a single new value, try to use the standard array.map()
.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。