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.
{{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.
index
Optional- The index of the current element being processed in the array.
array
Optional- The array
map
was called upon.
thisArg
Optional- Value to use as
this
when 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 flat
of depth 1.
Examples
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 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(" ")
Notice, the output list length can be different from the input list length.
Alternative
reduce
and concat
var arr1 = arr1.flatMap(x => [x * 2] // is equivalent to arr1.reduce((acc, x) => acc.concat([x * 2]
Specifications
Specification | Status | Comment |
---|---|---|
Array.prototype.flatMap proposal |
Finished (4) |
Browser compatibility
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Basic support | Chrome Full support 69 | Edge No support No | Firefox Full support 62 | IE No support No | Opera Full support 56 | Safari Full support 12 | WebView Android Full support 69 | Chrome Android Full support 69 | Edge Mobile No support No | Firefox Android Full support 62 | Opera Android Full support 56 | Safari iOS Full support 12 | Samsung Internet Android No support No | nodejs Full support 11.0.0 |
Legend
- Full support
- Full support
- No support
- No support