JavaScript Array flatMap() Method

JavaScript array flatMap() method is used to map all array elements and then flattens it into a new array. This method is a combination of map() and flat() methods and doesn’t modify the original array. 

Syntax

let new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
  // return element for new_array
}[, thisArg])

Parameters

  1. currentValue(required): It is the current element being processed in the array.
  2. index(optional): It is the index of the current element being processed in the array.
  3. array(optional): It is the array on which the map() function is called.

thisValue(optional): It is a value to use as this when executing the function.

Return Value

It returned a new array with each element resulting from the callback function and flattened to a depth 1.

Visual RepresentationVisual Representation of JavaScript Array flatMap() Method

Example 1: How to Use Array flatMap() method

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

let arrB = arrA.flatMap(x => [x + 2]);
console.log(arrB);


let arrC = arrA.flatMap(x => [x * 2]);
console.log(arrC);

let arrD = arrA.flatMap(x => [x - 1]);
console.log(arrD);

Output

[ 3, 4, 5, 6 ]
[ 2, 4, 6, 8 ]
[ 0, 1, 2, 3 ]

Example 2: Generate a list of words from a list of sentences

const arr1 = ["Hello world", "", "My friend"];

console.log(arr1.map((x) => x.split(" ")));

console.log(arr1.flatMap((x) => x.split(" ")));

Output

[ [ 'Hello', 'world' ], [ '' ], [ 'My', 'friend' ] ]
[ 'Hello', 'world', '', 'My', 'friend' ]

Example 3: Using sparse arrays

const arr1 = [1, 2, , 19, 21];

console.log(arr1.flatMap((x) => [x, x * 2]));

console.log(arr1.flatMap((x) => [, x * 2]));

Output

[
  1, 2, 2, 4,
  19, 38, 21, 42
]

[ 2, 4, 38, 42 ]

Example 4: Calling flatMap() on non-array objects

const arrayLike = {
  length: 3,
  0: 11,
  1: 19,
  2: 21,
};
console.log(Array.prototype.flatMap.call(arrayLike, (x) => [x, x * 2]));

// Array-like objects returned from the callback won't be flattened
console.log(
  Array.prototype.flatMap.call(arrayLike, (x) => ({
    length: 1,
    0: x,
  })),
);

Output

[ 11, 22, 19, 38, 21, 42 ]

[
  { '0': 11, length: 1 },
  { '0': 19, length: 1 },
  { '0': 21, length: 1 }
]

Browser Compatibility

  1. Google Chrome 69 and above
  2. Edge 79 and above
  3. Firefox 62 and above
  4. Opera 56 and above
  5. Safari 12 and above

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.