📘arr.flatMap()
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
JS ⟩ object ⟩ built-in ⟩ array ⟩ method ⟩ .flatMap()
arr.flatMap(f)
is the same as arr.map(f).flat()
.
['hello world', 'how are you'].flatMap(str => str.split(' ')),
// [ 'hello', 'world', 'how', 'are', 'you' ]
flatMap() allows each element to map to any number of elements.
replit ⟩ arr.flatMap()
// ⭐ "flatMap" as "filter + map"
[-2, -1, 1, 2].flatMap(x => x < 0 ? [] : Math.sqrt(x)),
// [-2, -1, 1, 2]
// map : [[], [], 1, 1.41421]