JavaScript Array flatMap() Method

JavaScript Array flatMap() Method first of all map every element with the help of mapping function, then flattens the input array element into a new array. 

The 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.

Syntax

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 this when executing callback.

JavaScript Array flatMap() Method can be used to flatten the array of depth 1 only because it calls a map() function followed by a flat() function with a depth of 1.

The flatMap() method does not change the original array.

Return value

Returns a new array after mapping every element using callback and flattening it to a depth of 1.

Example

let arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]);
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// only one level is flattened
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]