JavaScript - Array flatMap() Method
In JavaScript, the Array.flatMap() method is used to create a flat array by applying a callback function to each element of the original array. It doesn't modify the original array instead, it returns a new array with the results of applying the provided callback function to each element. This method does not execute the function for empty array elements.
Note − The flatMap() method is equivalent to "array.map().flat()".
Syntax
Following is the syntax of JavaScript Array flatMap() method −
array.flatMap(callbackFn (element, index, array), thisArg);
Parameters
This method accepts two parameters. The same is described below −
- callbackfn − This is a callback function that will be called once for each element in the array. It further takes three arguments −
- element − The current element being processed in the array.
- index − The index of the current element being processed.
- array − The array of the current element.
- thisArg (optional) − It specifies a value passed to the function to be used as its this value.
Return value
This method returns a new array with each element being the result of calling the provided function on each element of the original array, and flattening the result.
Examples
Example 1
In the following example, we provide a callback function to the flatMap() method where it multiplies each element in the specified array by the number "2" and flattens the array.
<html>
<body>
<p id="demo"></p>
<script>
const numbers = [5, 10, 20, 30, 40];
let result = numbers.flatMap( num => [num * 2]);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Output
As we can see the output, all the array elements are multipled by 2 and resulted in a new flat array.
10,20,40,60,80
Example 2
Here, we are iterating through each element of the specified nested array, multiplying them with the number 2 and returning the flattened array.
<html>
<body>
<p id="demo"></p>
<script>
const nestedArray = [[1, 2], [3, 4], [5, 6]];
let result = nestedArray.flatMap(innerArray => innerArray.map(num => num * 2));
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Output
After execution, the result will be a flattened array containing the doubled values.
2,4,6,8,10,12
Example 3
The flatMap() method automatically removes empty elements from the resulting array.
<html>
<body>
<p id="demo"></p>
<script>
const numbers = [5, , , 11, 15];
let result = numbers.flatMap(num => num ? [num * 2] : []);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Output
As we can see the output, the empty elements has been eliminated.
10,22,30