Array.prototype.flatMap
Maps each element with a function and flattens the result one level.
Available since: ES2019
Syntax
array.flatMap(callbackFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| callbackFn | Function | A function that returns a value or an array of values for each element. |
Return value
ArrayA new array flattened one level.
Examples
All the words from several phrases:
const phrases = ['hello world', 'good morning'];
console.log(phrases.flatMap((phrase) => phrase.split(' ')));Output:
[
"hello",
"world",
"good",
"morning"
]An empty array removes an element, two elements double it:
const numbers = [1, -2, 3];
console.log(numbers.flatMap((n) => (n < 0 ? [] : [n, n])).join(', '));Output:
1, 1, 3, 3Notes
It is the same as map() followed by flat(), but in one pass.
See also
- Array.prototype.map — Creates a new array by transforming every element.
- Array.prototype.flat — Flattens nested arrays into one.
Related recipes
In the tutorial
- map, filter and reduce — The three main array processing methods in JavaScript: transforming, selecting and reducing to a single value.