Array.prototype.flatMap()
Maps each element with a callback then flattens the result by one level.
Syntax
arr.flatMap(callback, thisArg) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
callback | Function | Yes | Function called with (element, index, array). May return a value or an array. |
thisArg | any | No | Value to use as `this` when executing the callback. |
Returns
Array — A new array with each callback result flattened by one level.
Examples
console.log([1, 2, 3].flatMap(n => [n, n * 2]));
Output
[ 1, 2, 2, 4, 3, 6 ]
console.log(['a b', 'c'].flatMap(s => s.split(' ')));
Output
[ 'a', 'b', 'c' ]
Notes
Equivalent to `.map(fn).flat(1)` but more efficient. Only flattens one level.
Returning an empty array effectively removes an element.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 69 |
| firefox | 62 |
| safari | 12 |
| edge | 79 |
| node | 11 |