Array.flatMap()
The Array.flatMap()
method in JavaScript first maps each element of an array using a provided callback function and then flattens the result into a new array. This method combines the functionality of map()
and flat()
into a single operation, with a depth of 1 for flattening.
Syntax
flatMap(callbackFn)
flatMap(callbackFn, thisArg)
Parameters
Parameter | Description |
---|---|
callbackFn | A function that is called for every element of the array. It produces a new array (or other values) for each element. |
thisArg | Optional. A value to use as this when executing callbackFn . |
Return Value
The flatMap()
method returns a new array with the results of calling callbackFn
on each element, flattened to a depth of 1.
Examples
1. Mapping and Flattening a Nested Array
This example demonstrates how flatMap()
maps each element and flattens the result into a single array.
const numbers = [1, 2, 3];
const result = numbers.flatMap(num => [num, num * 2]);
console.log(result);
Output
[1, 2, 2, 4, 3, 6]
numbers.flatMap(num => [num, num * 2])
maps each number to a two-element array and flattens the result.
2. Removing Empty Elements
The flatMap()
method can be used to filter out empty elements during the mapping process.
const words = ['hello', '', 'world'];
const result = words.flatMap(word => word ? [word] : []);
console.log(result);
Output
["hello", "world"]
- Non-empty strings are included, while empty strings are filtered out.
3. Flattening Nested Arrays
Using flatMap()
to flatten nested arrays directly.
const nested = [[1, 2], [3, 4], [5, 6]];
const result = nested.flatMap(arr => arr);
console.log(result);
Output
[1, 2, 3, 4, 5, 6]
Each nested array is directly flattened into the new array.
4. Using thisArg
in flatMap()
The thisArg
parameter specifies the value of this
when executing callbackFn
.
const multiplier = {
factor: 2,
};
const numbers = [1, 2, 3];
const result = numbers.flatMap(function (num) {
return [num * this.factor];
}, multiplier);
console.log(result);
Output
[2, 4, 6]
The thisArg
object, multiplier
, is used as the this
value inside the callbackFn
.