This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The 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]) callbackcurrentValueindexOptional
arrayOptional
map was called upon.thisArgOptional
this when executing callback.A new array with each element being the result of the callback function and flattened to a depth of 1.
See 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.
map and flatMap
let arr1 = x => [x * 2] // [[2], [4], [6], [8]] arr1.flatMap(x => [x * 2] // 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 showing usecase of flatMap better.
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(" ") Notice, the output list length can be different from the input list length.
reduce and concat
var arr1 = arr1.flatMap(x => [x * 2] // is equivalent to arr1.reduce((acc, x) => acc.concat([x * 2]
| Specification | Status | Comment |
|---|---|---|
Array.prototype.flatMap proposal | Candidate (3) |
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | 69 | No | 62 | No | 56 | 12 |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | 69 | 69 | No | 62 | 56 | 12 | No |
| Server | |
|---|---|
| Node.js | |
| Basic support | No |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap