Array.flat()
The Array.flat()
method in JavaScript creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. It simplifies handling nested arrays by flattening them into a single array or reducing their depth.
Syntax
flat()
flat(depth)
Parameters
Parameter | Description |
---|---|
depth (optional) | An integer specifying how deep the nested arrays should be flattened. Defaults to 1 if not provided. |
Return Value
The flat()
method returns a new array with the sub-array elements concatenated into it up to the specified depth.
Examples
1. Flattening a Nested Array to Default Depth
This example demonstrates the default behavior of flat()
, which flattens the array one level deep.
const nestedArray = [1, [2, [3, 4]]];
const result = nestedArray.flat();
console.log(result);
Output
[1, 2, [3, 4]]
The flat()
method flattens only the first level of the nested array.
2. Flattening a Nested Array to a Specific Depth
You can specify the depth to flatten the array using the depth
parameter.
const nestedArray = [1, [2, [3, [4, 5]]]];
const result = nestedArray.flat(2);
console.log(result);
Output
[1, 2, 3, [4, 5]]
Here, the array is flattened up to two levels deep.
3. Fully Flattening a Deeply Nested Array
To completely flatten an array regardless of its depth, pass Infinity
as the depth.
const nestedArray = [1, [2, [3, [4, [5]]]]];
const result = nestedArray.flat(Infinity);
console.log(result);
Output
[1, 2, 3, 4, 5]
Using Infinity
flattens the array completely into a single level.
4. Flattening an Array with Empty Slots
The flat()
method also removes empty slots in arrays while flattening.
const arrayWithHoles = [1, , 3, [4, , 6]];
const result = arrayWithHoles.flat();
console.log(result);
Output
[1, 3, 4, 6]
Notice that the empty slots are removed in the resulting array.