Open In App

What is Array.flatMap() in JavaScript?

Array.flatMap() is a method introduced in ECMAScript 2019 (ES10) that combines the functionalities of map() and flat() methods. It first maps each element of an array using a mapping function, then flattens the result into a new array. This method is particularly useful when you want to apply a transformation to each element of an array and flatten the resulting arrays into a single array.

Syntax:

array.flatMap(callbackFn[, thisArg])

Parameters:

Example: Here, the flatMap() method is called on the arr array with a callback function that doubles each element of the array and creates a new array containing both the original element and its doubled value.






const arr = [1, 2, 3];
 
const result = arr.flatMap(x => [x, x * 2]);
 
console.log(result);

Output
[ 1, 2, 2, 4, 3, 6 ]




Article Tags :