JS: Array.prototype.flatMap
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:
- currentElement
- currentIndex
- 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.