The flatMap() method in JavaScript is used to first map each element using a mapping function, then flatten the result into a new array. It combines the functionality of map() and flat() into a single method.
Syntax
array.flatMap(callback(currentValue, index, array), thisArg);
Parameters
Parameters | Descriptions |
---|---|
callback | A function that produces an element of the new array. It takes three arguments: |
currentValue | The current element being processed in the array. |
index (Optional) | The index of the current element being processed in the array. |
array (Optional) | The array flatMap() was called upon. |
thisArg (Optional) | A value to use as this when executing the callback function. |
Return Value
Return Type | Description |
---|---|
Array | A new array with each element being the result of the callback function and flattened to a depth of 1. |
Example 1: Using flatMap() to Flatten an Array of Arrays
This code demonstrates how to use the flatMap() method to flatten an array of arrays.
let arrays = [[1, 2], [3, 4], [5, 6]]; let flattenedArray = arrays.flatMap(function(arr) { return arr; }); console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]
Example 2: Using flatMap() with Mapping Function
You can also use flatMap() with a mapping function to manipulate each element before flattening the array.
let numbers = [1, 2, 3]; let doubledNumbers = numbers.flatMap(function(num) { return [num, num * 2]; }); console.log(doubledNumbers); // Output: [1, 2, 2, 4, 3, 6]
Example 3: Using Arrow Function
You can use an arrow function for more concise code.
let numbers = [1, 2, 3]; let doubledNumbers = numbers.flatMap(num => [num, num * 2]); console.log(doubledNumbers); // Output: [1, 2, 2, 4, 3, 6]
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
69 | 79 | 62 | 56 | 12 |