JavaScript Array flatMap() Method
The flatMap() method is a combination of flat() and map() methods. This method initially maps each array element through a mapping function, then flatten up the array with depth value as 1.
Syntax
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 returns a new array where each element is the result of the callback function.
JavaScript Array flatMap() Method Examples
Let’s see the below examples to understand better:
Example1
It is a simple example to know the use of flatMap() method.
Output:
Example2
Using flatMap() method with two different array elements.
Output:
Example3
This example shows the name of the fruit which each member likes.
Output:
Example4
An example to split the sentences into individual words.
Output:
It is clear in the output that each sentence is seperated from one another and forming individual word.