The flatMap function is essentially a fusion of the flat and map functions. It begins by applying a mapping function to each element of the array, and subsequently flattens the resulting array to a depth of 1.
Syntax
var newArr=arr.flatMap(function callback(currentValue[ , index[ , array]])
{
return element
} [ , thisArg])
Parameters
callback - It is a function which produces an element for the newly created array and carries the following three arguments:
- currentValue: It is the current array element that is in processing.
- index: It is the index value of the current array element in process. It is an optional argument.
- array: It is an optional argument where the array map is called upon.
- thisArg: It is also an optional argument whose value is used as 'this' when we execute the callback function.
Return
It produces a fresh array in which every element corresponds to the output of the callback function.
JavaScript Array flatMap Method Examples
Let us examine the following examples for a clearer understanding:
Example1
A straightforward illustration demonstrates the application of the flatMap function.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr=[2,4,6,8];
document.write(arr.flatMap(x=>[[x/2]]));
</script>
</body>
</html>
Output:
Example2
Applying the flatMap Function with Distinct Array Elements.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr1=['a','b','c','d'];
var arr2=[1,2,3,4];
var newArr=arr1.flatMap((arr1,index)=>[arr1,arr2[index]]); //It will map and flatten arr1 and arr2.
document.write("After applying the method <br>" +newArr);
</script>
</body>
</html>
Output:
Example3
This illustration demonstrates the preferred fruit of each individual member.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr=['James','John','Mary','Renzo'];
var arr1=['Apple','Pineapple','Guava','Grapes'];
document.write("The resultant will display the fruits liked by each person <br>");
var newArr=arr.flatMap((arr,index)=>[arr,arr1[index]]);
document.write("<br>"+newArr);
</script>
</body>
</html>
Output:
Example4
A demonstration to separate sentences into distinct words.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr = ["This is", , "logic-practice.com"];
var newArr=arr.flatMap(x => x.split(" "));
document.write("This will split the sentences into individual words: "+newArr);
</script>
</body>
</html>
Output:
The output clearly indicates that each sentence is distinct from one another, resulting in the formation of individual words.