JavaScript Reference ยท Array
JavaScript Array flatMap() method
Reference for JavaScript Array flatMap(): map each element to zero, one or many values and flatten the result one level, with examples and pitfalls.
The flatMap() method calls a callback on every element, like map(), and then flattens the result by exactly one level. Each callback can therefore return a single value, an array of several values, or an empty array to contribute nothing.
That makes it a compact tool for "one-to-many" transformations (splitting, expanding) and for combining a map and a filter in one pass. It returns a new array and does not change the original.
["a b", "c"].flatMap((s) => s.split(" ")); // ["a", "b", "c"]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
flatMap(callbackFn) flatMap(callbackFn, thisArg)
| Name | Description |
|---|---|
callbackFn |
Called as callbackFn(element, index, array). Return a value, or an array of values to be spread into the result. |
thisArg |
Optional. Value used as this inside callbackFn (ignored by arrow functions). |
Return value: a new array of the mapped, flattened results.
Exceptions: a TypeError if callbackFn is not a function.
Usage notes
- Only one level is flattened. Returning
[[n]]produces[[n]]-style nesting in the result: the outer array is removed, the inner stays. For deeper flattening, callflat()afterward. - Return
[]to skip an element and[value]to keep one. This is the filter-and-map idiom, though afilter()followed bymap()is often more readable. - Only arrays are spread. A non-array return value is added as is; array-like objects and strings are not flattened.
- Holes are skipped, like in
map(). - Equivalent:
arr.flatMap(fn)behaves likearr.map(fn).flat()but avoids the intermediate array. - Performance: creating a tiny array for every element has a cost. For hot loops over huge arrays, a plain loop or
reduce()that pushes into one array can be faster. - Cartesian products: nesting
flatMap()andmap()produces every combination, as in the pairs example.
Browser support
flatMap() is supported in current browsers. It is newer than map() and filter(), so check a compatibility table for very old environments.