4
Author: Dmitri Pavlutin
Translator: Front-end Xiaozhi
Source: dmitripavlutin
If you have dreams and dry goods, you can search for [Great Relocation to the World] on WeChat and pay attention to this Shuwanzhi who is still washing dishes in the early hours of the morning.
This article https://github.com/qq449245884/xiaozhi . There are complete test sites, materials and my series of articles for interviews with first-tier manufacturers.

array.map() is a very useful map function: it takes an array and a map function, and returns a new map array.

However, there is an alternative to array.map() : array.flatMap() (available since ES2019). This method gives us the ability to map, but also to remove or even add new items to the resulting map array.

1. Smarter mapper

Having an array of numbers, how do we create a new array with each number doubled?

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]

Address: https://jsfiddle.net/dmitri_pavlutin/7g5fz93y/

numbers.map(number => 2 * number) the number array to a new array where each number is doubled.

For cases where a one-to-one mapping is required, that is, the mapped array has the same number of items as the original array, array.map() works very well.

But what if we need to double the numbers of an array while jumping to the entry 0

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 we can use a combination of array.map() and array.filter()

const numbers = [0, 3, 6];
const doubled = numbers
  .filter(n => n !== 0)
  .map(n => n * 2);
console.log(doubled); // logs [6, 12]

Case address: https://jsfiddle.net/dmitri_pavlutin/cvtjyLpo/

array.map() and array.filter() , but is there a shorter way?

for sure. Using the array.flatMap() method, you can perform the mapping and delete items with just one method call.

const numbers = [0, 3, 6];
const doubled = numbers.flatMap(number => {
  return number === 0 ? [] : [2 * number];
});
console.log(doubled); // logs [6, 12]

Case address: https://jsfiddle.net/dmitri_pavlutin/j945qunz/

By just using numbers.flatMap() , you can map one array to another, but also skip certain elements from the map.

Next, let's take a more detailed look at how array.flatMap() works.

2. array.flatMap()

array.flatMap() function accepts a callback function as parameter 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 item in the original array, with 3 parameters: the current item, the index, and the original array. Then, the array returned by the callback function is flattened by 1 layer, and the resulting items are added to the mapped array.

Additionally, the method accepts a second optional parameter representing the this value inside the callback.

The easiest way to use array.flatmap() is to flatten the array containing the items

const arrays = [[2, 4], [6]];
const flatten = arrays.flatMap(item => item);
console.log(flatten); // logs [2, 4, 6]

Case address: https://jsfiddle.net/dmitri_pavlutin/5rwvcz17/

But the array.flatMap() can do much more than simply flatten. By controlling the number of array items returned from the callback:

  • Remove the item from the result array by returning an empty array
  • Modify the mapped item by returning an array [newValue]
  • Add a new item by returning an array with multiple values: [newValue1, newValue2, ...]

For example, as you saw in the previous section, a new array can be created by doubling the items, but also removing 0 .

const numbers = [0, 3, 6];
const doubled = numbers.flatMap(number => {
  return number === 0 ? [] : [2 * number];
});
console.log(doubled); // logs [6, 12]

Now, let's see how it works.

If the current item is 0 , the callback function returns an empty array [] . This means that when flattened, the empty array [] provides no value.

[2 * number] if the current iteration item is nonzero. When flattening the [2 * number] 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]

address: 161f8780bdf161 https://jsfiddle.net/dmitri_pavlutin/k7p2x1ar/

3: Summary

array.flatMap() method is a good idea if you want to map an array into a new array while still controlling how many items you want to add to the new mapped array.

array.flatMap(callback) 's callback function is called with 3 parameters: the current iteration's item, the index, and the original array. Then, the array returned from the callback function 1 deep, and the resulting items are inserted into the resulting mapped array.

~End, I'm Shawanzhi, let's wash the brush together in the new year! ! ! ! ! !


code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, I recommend a useful bug monitoring tool Fundebug .

Original: https://dmitripavltin.com/javascrit-array-flatmap/

comminicate

If you have dreams and dry goods, search on [Moving the World] still washing dishes in the early morning.

This article https://github.com/qq449245884/xiaozhi . There are complete test sites, materials and my series of articles for interviews with first-tier manufacturers.


王大冶
68k 声望104.9k 粉丝