JavaScript(JS) array method - flatmap

The flatMap() method is an array method in JavaScript that maps each element in an array to a new array, and then flattens the result into a single array. It performs a combination of the map() and flat() methods in a single step.

Here's the syntax of the flatMap() method:

ref‮i:ot re‬giftidea.com
array.flatMap(callback);
  • array is the array that the flatMap() method is called on.
  • callback is a function that is called for each element in the array. The function should return an array, which will be flattened and concatenated into the final result array.

The flatMap() method does not modify the original array. It returns a new flattened array.

Here's an example of how to use the flatMap() method:

let array = [1, 2, 3];

let mappedArray = array.flatMap(x => [x, x * 2]);

console.log(mappedArray); // [1, 2, 2, 4, 3, 6]

In this example, we have an array array containing the elements [1, 2, 3]. We use the flatMap() method to map each element to an array containing the element and its double ([x, x * 2]). The flatMap() method then flattens the resulting nested arrays into a single level array. The console.log() statement outputs the value of mappedArray, which is [1, 2, 2, 4, 3, 6].

Note that the flatMap() method was introduced in ECMAScript 2019, so it may not be supported by older browsers. If you need to achieve the same functionality in older browsers, you can use a combination of the map() and concat() methods.