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 flatten of depth 1, but flatMap is quite often useful and merging both into one method is slightly more efficient.
{{EmbedInteractiveExample("pages/js/array-flatmap.html")}}
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
// return element for new_array
}[, thisArg])
Parameters
callback- Function that produces an element of the new Array, taking three arguments:
currentValue- The current element being processed in the array.
indexOptional- The index of the current element being processed in the array.
arrayOptional- The array
mapwas called upon.
thisArgOptional- Value to use as
thiswhen executingcallback.
Return value
A new array with each element being the result of the callback function and flattened to a depth of 1.
Description
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 flatten of depth 1.
Examples
Map and flatMap
var 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]]
Specifications
| Specification | Status | Comment |
|---|---|---|
Array.prototype.flatMap proposal |
Draft |
Browser compatibility
| Feature | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
| Basic support | No | No | No1 | No | No | No |
| Feature | Android webview | Chrome for Android | Edge mobile | Firefox for Android | Opera Android | iOS Safari | Samsung Internet |
|---|---|---|---|---|---|---|---|
| Basic support | No | No | No | No1 | No | No | ? |
1. Available in Firefox Nightly only. See bug 1435813 for status on enabling this by default.