The flatMap() method of the Array class in JavaScript returns a new array formed by applying a given callback function to each element of the calling array, and then flattening the result by one level.
There are 2 variations for the syntax of Array.flatMap() method. They are:
flatMap(callbackFn)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to apply to each element in the array. It takes three arguments: element, index, and array. |
This method returns a new array formed by applying a given callback function to each element of the calling array, and then flattening the result by one level.
Returns value of type Array
.
flatMap(callbackFn, thisArg)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to apply to each element in the array. It takes three arguments: element, index, and array. |
thisArg | optional | A value to use as this when executing callbackFn. |
This method returns a new array formed by applying a given callback function to each element of the calling array, and then flattening the result by one level, using thisArg as the value of this inside callbackFn.
Returns value of type Array
.
In JavaScript, we can use the flatMap() method to double the values of an array and flatten the result by one level.
For example,
const arr = [1, 2, 3];
const double = element => [element * 2];
const doubledAndFlattened = arr.flatMap(double);
console.log(doubledAndFlattened);
[2, 4, 6]
We can use the flatMap() method to map an array of strings to their lengths and flatten the result by one level.
For example,
const strArr = ['apple', 'banana', 'cherry'];
const getLength = element => [element.length];
const lengths = strArr.flatMap(getLength);
console.log(lengths);
[5, 6, 6]
We can use the flatMap() method with a thisArg to map and flatten an array using a specific context.
For example,
const arr = [1, 2, 3];
const context = { multiplier: 3 };
function multiply(element) {
return [element * this.multiplier];
}
const multipliedAndFlattened = arr.flatMap(multiply, context);
console.log(multipliedAndFlattened);
[3, 6, 9]
In this JavaScript tutorial, we learned about flatMap() method of Array: the syntax and few working examples with output and detailed explanation for each example.