JavaScript Array flat() method
The flat()
method in JavaScript is used to create a new array with all sub-array elements concatenated into it recursively up to a specified depth. This method is particularly useful for flattening nested arrays, allowing you to reduce the depth of nested structures in a straightforward manner.
Syntax:
depth
(optional): A non-negative integer that specifies how deep a nested array structure should be flattened. The default is1
, which means only the first level of nested arrays will be flattened. If omitted, it flattens one level by default.
Return Value:
- A new array that is a flattened version of the original array, with elements from sub-arrays merged into it.
Key Points:
- The
flat()
method does not modify the original array; it returns a new array instead. - If
depth
is set toInfinity
, it will recursively flatten the array regardless of how deeply nested it is. - Non-array items are included as-is in the new array.
Example 1: Basic usage
Example 2: Specifying depth
Example 3: Flattening deeply nested arrays
Example 4: Non-array elements
Example 5: Empty arrays
Summary:
- The
flat()
method provides an easy way to flatten nested arrays into a single array, which can simplify data structures for processing. - It is especially useful when working with data that can have variable levels of nesting, making it easier to handle in various applications.
- Since it creates a new array, the original structure remains unchanged, allowing for flexibility in manipulating data.