Flattening an Array
Flattening an Array: flat()
The flat()
method in Javascript is used to flatten an array, meaning it merges nested sub-arrays into a single array up to a specified depth. This method is helpful when working with multidimentional arrays and merging arrays with nested elements.
The flat()
method takes depth as an optional argument. By default, the depth is set to 1.
Examples
Example 1, using flat()
to flatten an array:
In this example, the flat by default takes the depth as 1 and flattens the array to one level deep.
Example 2, using flat()
with a depth argument:
In this example, using the flat method without the depth argument flattens the array to only one level deep. Calling flat()
without specifying a depth will flatten only the first level of nested arrays. This means it unpacks [3, 4] from the array, but leaves [5, 6] untouched, as itβs inside another nested array.
Hence the result [1, 2, 3, 4, [5, 6]] β where [5, 6] is still nested.
But with the depth argument set to 2, flat(2)
will flatten the array up to two levels deep. This means it will flatten both the first level ([3, 4]) and the second level ([5, 6]) of nesting, resulting in a completely flattened array in this case.
Hence the result [1, 2, 3, 4, 5, 6] β where all elements are at the top level.
Example 3, using flat()
in an array which has empty slots (Sparse Array):
Using flat()
method on a sparse array not only flattens nested arrays but also removes empty slots from sparse arrays. This behavior is particularly useful when you want to ensure that your array contains only defined values.
Notes
- Setting the depth argument to
Infinity
, allows you to completely flatten an array. It ensures that no matter how deeply nested the elements are, they will all be accessible at the top level of the resulting array.