flatMap()

ES2019+

Returns a new array formed by applying a given callback function to each element of the array, then flattening the result by one level.

Syntax

array.flatMap(callback(element, index, array), thisArg)

Parameters

callback Function

Function that produces an element of the new Array

Return Value

Array

A new array with mapped and flattened elements

Examples

JavaScript
const sentences = ['Hello World', 'How are you'];
const words = sentences.flatMap(s => s.split(' '));
console.log(words);
Output:
// ['Hello', 'World', 'How', 'are', 'you']

Related Methods