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.
JavaScript, Loop, Iteration
JS Array.prototype
- JS: Array.prototype.length
- JS: Array.prototype.constructor
- JS: Array.prototype.values
- JS: Array.prototype.pop
- JS: Array.prototype.push
- JS: Array.prototype.shift
- JS: Array.prototype.unshift
- JS: Array.prototype.splice
- JS: Array.prototype.fill
- JS: Array.prototype.copyWithin
- JS: Array.prototype.concat
- JS: Array.prototype.slice
- JS: Array.prototype.entries
- JS: Array.prototype.keys
- JS: Array.prototype.values
- JS: Array.prototype.map
- JS: Array.prototype.forEach
- JS: Array.prototype.filter
- JS: Array.prototype.sort
- JS: Array.prototype.reverse
- JS: Array.prototype.includes
- JS: Array.prototype.indexOf
- JS: Array.prototype.lastIndexOf
- JS: Array.prototype.find
- JS: Array.prototype.findIndex
- JS: Array.prototype.some
- JS: Array.prototype.every
- JS: Array.prototype.reduce
- JS: Array.prototype.reduceRight
- JS: Array.prototype.join
- JS: Array.prototype.toString
- JS: Array.prototype.flat (Flatten Array)
- JS: Array.prototype.flatMap