JS: Array.prototype.flatMap

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2019)

xArray.flatMap(f)
  • Apply function to every element x of the array, if result is array, flatten it one level. if result is empty array, effectively means remove x.
  • Return the new array.
  • Original array is not changed.

f is given 3 args: currentElement currentIndex xArray

💡 TIP: flatMap is useful when you want to insert or remove items at some elements in the array. To remove item, just return a empty array.

// if number is even, repeat it, else delete it
console.log(
  JSON.stringify(
    [1, 2, 3, 4, 5].flatMap(
      (x) => ((x % 2 === 0) ? [x, x] : []),
    ),
  ) === `[2,2,4,4]`,
);
xArray.flatMap(f, thisArg)

Use thisArg for this (binding) of f. Default to undefined.

JavaScript. Loop, Iteration

JavaScript. Map, Iteration, Reduce