Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.flatMap

Maps each element with a function and flattens the result one level.

Available since: ES2019

Syntax

array.flatMap(callbackFn)

Parameters

ParameterTypeDescription
callbackFnFunctionA 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, 3

Notes

It is the same as map() followed by flat(), but in one pass.

See also

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.

Thanks for reading!

Donate to the site — we work hard for you.