Flattening and Mapping a Nested Array
Flattening and Mapping a Nested Array: flatMap()
The flatMap()
method in JavaScript combines the functionality of map()
and flat()
into one. It maps each element using a mapping function and then flattens the result into a new array. By default, it flattens the array one level deep, making it useful for dealing with nested arrays while performing a transformation.
The flatMap()
method does not take a depth argument; it flattens the array by exactly one level.
Examples
Example 1, using flatMap()
to map and flatten a nested array:
In this example, the flatMap()
method is used to flatten each sub-array in arr by one level. The callback simply returns the elements as they are, and flatMap() flattens the resulting nested arrays.
Example 2, using flatMap()
to handle nested arrays and sparse arrays:
In this example, flatMap()
flattens the nested arrays while automatically removing empty slots from sparse arrays.
Example 3, using flatMap()
to concatenate and flatten strings in a nested array:
Here, each nested array is joined into a single string using join()
, and flatMap()
flattens the resulting array of strings into a single-level array.
Notes
- The
flatMap()
method is a combination ofmap()
followed byflat(1)
. - Itβs important to note that
flatMap()
only flattens by one level. If you need to flatten more deeply nested arrays, you should usemap()
followed byflat()
with the required depth.