0%

javascript-flatmap

JavaScript flatMap

flatMap is the combination of map and flat, It first maps each element using a mapping function, then flattens(only one level) the result into a new array. It’s the same as map followed by flat.

1
arr.flatMap(f); // is equal to arr.map(f).flat();

Note that flatMap only flattening one level

所以,flatMap最多只对二维数组有效,对于多维数组,可以使用arr.map(f).flat(Infinity)

以下代码的作用是,给定一个数组,将数组中每个元素和它的2倍放到一个新数组中,并将所有结果放到一个新数组中。

1
2
3
const arr = [1, 2, 3, 4, 5];
const result = arr.flatMap(x => [x, x * 2]);
console.log(result); // [1, 2, 2, 4, 3, 6, 4, 8, 5, 10]

is equal to

1
2
3
const arr = [1, 2, 3, 4, 5];
const result = arr.map(x => [x, x * 2]).flat();
console.log(result); // [1, 2, 2, 4, 3, 6, 4, 8, 5, 10]

看下面的例子,给定一个字符串数组,其中每个元素是一句话,我们需要将每个句子拆分成单词,并将所有单词放到一个新数组中。

1
2
3
4
5
6
7
8
const arr = [
'It is sunny today',
'I am happy',
'I am learning JavaScript'
];

const result = arr.flatMap(x => x.split(' '));
console.log(result); // ["It", "is", "sunny", "today", "I", "am", "happy", "I", "am", "learning", "JavaScript"]

is equal to

1
2
3
4
5
6
7
8
const arr = [
'It is sunny today',
'I am happy',
'I am learning JavaScript'
];

const result = arr.map(x => x.split(' ')).flat();
console.log(result); // ["It", "is", "sunny", "today", "I", "am", "happy", "I", "am", "learning", "JavaScript"]

Conclusion

So, When to use flatMap? When using Array.prototype.map the callback function usually return an element, but sometimes it returns an array, and you want to flatten the result. Then you can use flatMap to make the code more concise and readable.

当使用Array.prototype.map的回调函数返回数组时,你通常都要使用flatMap.