Array.flaMap() method is a combination
map() method and
flat() method. It first maps each element in an array using the mapping function, then flattens the array and results into a new array.
arr.flatMap(callback(currentValue, index, array),thisArg)
- callback – The function to initially execute on each array element. It takes in:
- currentValue – The current element being passed from the array.
- index (Optional) – The index of the current element being processed in the array.
- array (Optional) – The array map was called upon.
- thisArg (optional) – Value to use as
flatMap() method does not change the original array.
Returns a new array after mapping every element using
callback and flattening it to a depth of 1.
let arr1 = [1, 2, 3, 4]; arr1.map(x => [x * 2]); // [, , , ] arr1.flatMap(x => [x * 2]); // [2, 4, 6, 8] // only one level is flattened arr1.flatMap(x => [[x * 2]]); // [, , , ]