JS: Array.prototype.flatMap

By Xah Lee. Date: . Last updated: .

New in ES2019

Apply function f to every element of the array myArray, then flatten 1 level.

Return the new array.

myArray.flatMap(…) is same as myArray.map(…).flat()

[see JS: Array.prototype.flat]

Original array is not changed.

If thisArg is given, it will be used as this value of f. If it is not given, undefined is used.

[see JS: “this” Binding]

The function f is passed 3 args: • current_elementcurrent_indexmyArray.

const a1 = [[1,2],[[3],4]];

const a2 = a1.flatMap( ((x) => x[0]) );

// [ 1, 3 ]

For example with the passed function using more than 1 argument, or with thisArg, see JS: Array.prototype.map

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials