Master programming syntax, solve interactive challenges & run live code in Syntaxis Explore Arena →
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

NameTypeDescription
callbackFunctionFunction 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.