The flatMap()
method first maps each element of an array using a mapping function, then flattens it into a new array.
Example
// defining an array
let numbers = [1, 2, 3, 4, 5];
// each element of the array is squared and later flattened
const resultingArray = numbers.flatMap((x) => [x ** 2]);
console.log(resultingArray);
// Output:
// [ 1, 4, 9, 16, 25 ]
flatMap() Syntax
The syntax of the flatMap()
method is:
arr.flatMap(callback(currentValue),thisArg)
Here, arr is an array.
flatMap() Parameters
The flatMap()
method can take two parameters:
- callback - The callback function to initially execute on each array element. It takes in:
- currentValue - The current element being passed from the array.
- thisArg (optional) - Value to use as this when executing
callback
.
flatMap() Return Value
- Returns a new array after mapping every element using
callback
Notes:
- The
flatMap()
method does not change the original array. - The
flatMap()
method is equivalent toarray.map().flat()
.
Example 1: Using flatMap() Method
// defining an array
let numbers = [1, 2, 3, 4, 5];
// each element of the array is incremented by 1
// and later the array is flattened
let resultingArray = numbers.flatMap((element) => element + 1);
console.log(resultingArray);
Output
[ 2, 3, 4, 5, 6 ]
In the above example, we have used the flatMap()
method to increment every element of the numbers array by 1.
((element) => element + 1)
is a mapping function that is executed in every element of numbers.
The method returns a flattened array- [ 2, 3, 4, 5, 6 ]
i.e. each element is incremented by 1.
Example 2: Using flat() and map() Instead of flatMap()
The flatMap()
method is the combination of the flat()
and map()
methods. Instead of using the two methods, we can use the combined version i.e. flatMap()
.
// defining an array
let numbers = [1, 2, 3, 4, 5];
// incrementing each element of array using map()
let afterMapping = numbers.map((element) => element + 2);
// flattening the array using flat()
let afterFlattening = afterMapping.flat();
console.log(afterFlattening); // [ 3, 4, 5, 6, 7 ]
// using flatMap() instead of flat() and map()
let after_flatMap = numbers.flatMap((element) => element + 2);
console.log(after_flatMap); // [ 3, 4, 5, 6, 7 ]
Output
[ 3, 4, 5, 6, 7 ] [ 3, 4, 5, 6, 7 ]
Here at first, we have used the map()
and flat()
methods separately in the numbers array.
We have then used the flatMap()
method which first map()
the array and then it flat()
.
In both the cases, the method returns the same array- [ 3, 4, 5, 6, 7 ]
.
Also Read: