Reference / JavaScript
Array.prototype.flatMap()
Returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level.
Syntax
flatMap(callback: (currentValue: T, index: number, array: T[]) => U | ReadonlyArray<U>, thisArg?: any): U[]Parameters
| Name | Type | Description |
|---|---|---|
| callback | Function | Function that produces an array or element. |
Examples
Splitting sentences to words
const sentences = ['Hello world', 'Syntaxis learning'];
const words = sentences.flatMap(s => s.split(' '));
console.log(words); // ['Hello', 'world', 'Syntaxis', 'learning']Equivalent to map() followed by flat(1), but significantly more efficient.