flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient.

句法

var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])
					

参数

callback
Function that produces an element of the new Array, taking three arguments:
currentValue

The current element being processed in the array.

index 可选

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

array 可选
The array map was called upon.
thisArg 可选
Value to use as this when executing callback .

返回值

A new array with each element being the result of the callback function and flattened to a depth of 1.

描述

Array.prototype.map() for a detailed description of the callback function. The flatMap method is identical to a map followed by a call to flat of depth 1.

Alternative

reduce() and concat()

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, however, 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 just adding the new elements to the existing array.

Please do not add polyfills on this article. For reference, please check: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500

范例

map() and flatMap()

let 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]]
								

While the above could have been achieved by using map itself, here is an example that better showcases the use of flatMap .

Let's generate a list of words from a list of sentences.

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"]
								

Notice, the output list length can be different from the input list length.

For adding and removing items during a map()

flatMap can be used as a way to add and remove items (modify the number of items) during a map . In other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one . In this sense, it works like the opposite of filter . Simply return a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item.

// 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]
								

规范

规范
ECMAScript (ECMA-262)
The definition of 'Array.prototype.flatMap' in that specification.

浏览器兼容性

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
flatMap Chrome 69 Edge 79 Firefox 62 IE No Opera 56 Safari 12 WebView Android 69 Chrome Android 69 Firefox Android 62 Opera Android 48 Safari iOS 12 Samsung Internet Android 10.0 nodejs 11.0.0

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改:
  1. 标准内置对象
  2. Array
  3. 特性
    1. Array.prototype.length
    2. Array.prototype[@@unscopables]
  4. 方法
    1. Array.from()
    2. Array.isArray()
    3. Array.of()
    4. Array.prototype.concat()
    5. Array.prototype.copyWithin()
    6. Array.prototype.entries()
    7. Array.prototype.every()
    8. Array.prototype.fill()
    9. Array.prototype.filter()
    10. Array.prototype.find()
    11. Array.prototype.findIndex()
    12. Array.prototype.flat()
    13. Array.prototype.flatMap()
    14. Array.prototype.forEach()
    15. Array.prototype.includes()
    16. Array.prototype.indexOf()
    17. Array.prototype.join()
    18. Array.prototype.keys()
    19. Array.prototype.lastIndexOf()
    20. Array.prototype.map()
    21. Array.prototype.pop()
    22. Array.prototype.push()
    23. Array.prototype.reduce()
    24. Array.prototype.reduceRight()
    25. Array.prototype.reverse()
    26. Array.prototype.shift()
    27. Array.prototype.slice()
    28. Array.prototype.some()
    29. Array.prototype.sort()
    30. Array.prototype.splice()
    31. Array.prototype.toLocaleString()
    32. Array.prototype.toSource()
    33. Array.prototype.toString()
    34. Array.prototype.unshift()
    35. Array.prototype.values()
    36. Array.prototype[@@iterator]()
    37. get Array[@@species]
  5. 继承:
  6. Function
  7. 特性
    1. Function.arguments
    2. Function.caller
    3. Function.displayName
    4. Function.length
    5. Function.name
  8. 方法
    1. Function.prototype.apply()
    2. Function.prototype.bind()
    3. Function.prototype.call()
    4. Function.prototype.toSource()
    5. Function.prototype.toString()
  9. Object
  10. 特性
    1. Object.prototype.__proto__
    2. Object.prototype.constructor
  11. 方法
    1. Object.prototype.__defineGetter__()
    2. Object.prototype.__defineSetter__()
    3. Object.prototype.__lookupGetter__()
    4. Object.prototype.__lookupSetter__()
    5. Object.prototype.hasOwnProperty()
    6. Object.prototype.isPrototypeOf()
    7. Object.prototype.propertyIsEnumerable()
    8. Object.prototype.toLocaleString()
    9. Object.prototype.toSource()
    10. Object.prototype.toString()
    11. Object.prototype.valueOf()
    12. Object.setPrototypeOf()

Copyright  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1