JavaScript Array flatMap() method
The flatMap()
method in JavaScript is a combination of the map()
and flat()
methods. It first maps each element using a provided mapping function and then flattens the result into a new array. This method is useful for applying a transformation to each element and simultaneously flattening the result, particularly when the mapping function returns an array.
Syntax:
callback
: A function that is called for each element in the array. It takes three arguments:currentValue
: The current element being processed in the array.index
(optional): The index of the current element being processed.array
(optional): The array thatflatMap
was called upon.
thisArg
(optional): A value to use asthis
when executing the callback.
Return Value:
- A new array with the results of the callback function mapped and flattened.
Key Points:
- The
flatMap()
method first maps each element to a new value and then flattens the resulting array to a depth of 1. - It does not modify the original array; instead, it returns a new array.
- If the mapping function returns a non-array value, that value will still be included in the resulting array as-is.
Example 1: Basic usage
Example 2: Returning arrays from the callback
Example 3: Flattening nested structures
Example 4: Using objects
Example 5: Handling empty results
Summary:
- The
flatMap()
method provides a convenient way to map an array's elements to new values and flatten the results in a single step. - This method is particularly useful when each mapped element could generate multiple values (i.e., arrays) and you want to combine the results into a single array.
- It simplifies code by reducing the need for separate mapping and flattening operations.