JavaScript: Array.prototype.flatMap

By Xah Lee. Date: . Last updated: .

New in JS2019.

arrayX.flatMap(f)
  • Apply function to every element of the array, if result is array, flatten it one level.
  • Return the new array.
  • Original array is not changed.

The function f is passed 3 args:

  1. currentElement
  2. currentIndex
  3. arrayX

💡 TIP: flatMap is useful when you want to insert items at some elements in the array.

// if number is even, add "a" after it
const xx = [1, 2, 3, 4, 5];
const yy = (xx.flatMap((x) => ((x % 2 === 0) ? [x, "a"] : x)));
console.log(JSON.stringify(yy) === '[1,2,"a",3,4,"a",5]');
arrayX.flatMap(f, thisArg)

Use thisArg for this Binding of f. If it is not given, undefined is used.

JavaScript: Array, add/remove items

JavaScript Loop, Iteration

BUY ΣJS JavaScript in Depth