What is Array.flatMap() in JavaScript?
Last Updated :
14 Feb, 2024
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:
callbackFn
: A function that accepts up to three arguments: the current element being processed, the index of the current element, and the array being mapped.
thisArg
(optional): An object to which this
a keyword can refer to inside the callbackFn
.
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.
Javascript
const arr = [1, 2, 3];
const result = arr.flatMap(x => [x, x * 2]);
console.log(result);
|
Output
[ 1, 2, 2, 4, 3, 6 ]
Share your thoughts in the comments
Please Login to comment...