JavaScript flatMap()Method

Array 对象参考手册JavaScript Array Object

Example

Map each element using a mapping function, then flatten the result into a new array:

const arr1 = [1, 2, [3], [4, 5], 6, []]; const flattened = arr1.flatMap(num => num); document.getElementById("demo").innerHTML = flattened;

Try it »

Definition and Usage

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is almost identical to map followed by a flat with a depth value of 1, but flatMap is usually slightly more efficient when combined into one method.

The flatMap() method returns a new array, where each element is the result of the callback function, and the structure depth value is 1.


Browser Support

The numbers in the table specify the first browser version that supports the method.

Method
flatMap() 45.0 12.0 32.0 9 25.0

Syntax

// 箭头函数
flatMap((currentValue) => { /* … */ } )
flatMap((currentValue, index) => { /* … */ } )
flatMap((currentValue, index, array) => { /* … */ } )

// 回调函数
flatMap(callbackFn)
flatMap(callbackFn, thisArg)

// 行内回调函数
flatMap(function(currentValue) { /* … */ })
flatMap(function(currentValue, index) { /* … */ })
flatMap(function(currentValue, index, array){ /* … */ })
flatMap(function(currentValue, index, array) { /* … */ }, thisArg)

Parameters

Parameters Description
callback

A function that can generate elements in a new array; it can accept three parameters:

currentValue

The current element being processed in the array

indexOptional

Optional. The index of the current element being processed in the array.

arrayOptional

Optional. The calledmaparray

thisArgOptional. The value of this to use when executing the callback function.

Technical Details

Return value: An array.
JavaScript Version: ECMAScript 6

More Examples

map() and flatMap()

Example

var arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]);
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// only one level is flattened
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]

Although the code above seems to work with both map and flatMap, this only shows how to use flatMap.

So, to better demonstrate the role of flatMap, below we split an array containing several sentences into a new array composed of individual words.

Example

let arr1 = ["it's Sunny in", "", "California"];

arr1.map(x => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap(x => x.split(" "));

// ["it's","Sunny","in", "", "California"]

Note that the output list length can be different from the input list length.

Add or remove some items during a map()

flatMap can be used to add or remove items during a map (that is, to modify the number of items). In other words, it allows you to traverse many items and turn them into other items (by handling them individually), rather than always being one-to-one. In this sense, its function is similar to the opposite of filter. Simply return a 1-element array to keep the item, return a multi-element array to add items, or return a 0-element array to remove the item.

Example

// Let's say we want to remove all the negative numbers and split the odd numbers into an even number and a 1
let a = [5, 4, -3, 20, 17, -33, -4, 18]
//       |\  \  x   |  | \   x   x   |
//      [4,1, 4,   20, 16, 1,       18]

a.flatMap( (n) =>
  (n < 0) ?      [] :
  (n % 2 == 0) ? [n] :
                 [n-1, 1]
)

// expected output: [4, 1, 4, 20, 16, 1, 18]

Alternatives

reduce() and concat()

Example

var arr = [1, 2, 3, 4];

arr.flatMap(x => [x, x * 2]);
// is equivalent to
arr.reduce((acc, x) => acc.concat([x, x * 2]), []);
// [1, 2, 2, 4, 3, 6, 4, 8]

Note that this is inefficient and should be avoided for large arrays: in each iteration, it creates a new temporary array that must be garbage-collected, and it copies elements from the current accumulator array into a new array instead of adding new elements to an existing array.



Array 对象参考手册JavaScript Array Object

Other Extensions