The flat() method in JavaScript is used to flatten a nested array structure. It creates a new array that is flattened to a certain depth, which is specified as an argument to the method. By default, flat() will flatten the array to a depth of 1 if no depth is provided.
Syntax
Array.flat( depth );
Parameters
Parameters | Description |
---|---|
depth (Optional) | The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. |
Return Value
Return Type | Description |
---|---|
Array | A new array with the sub-array elements concatenated |
Example 1: Flattening a Nested Array
This code demonstrates how to use the flat() method to flatten a nested array.
let nestedArray = [1, 2, [3, 4, [5, 6]]]; let flattenedArray = nestedArray.flat(); // Output: [1, 2, 3, 4, [5, 6]] console.log(flattenedArray);
Example 2: Flattening to a Custom Depth
You can also specify the depth to which the array should be flattened. In this example, the array is flattened to a depth of 2.
let nestedArray = [1, 2, [3, 4, [5, 6]]]; let flattenedArray = nestedArray.flat(2); // Output: [1, 2, 3, 4, 5, 6] console.log(flattenedArray);
Example 3: Flattening an Array of Mixed Values
The flat() method works with arrays containing a mix of values, including arrays and non-array values.
let mixedArray = [1, 2, [3, 4], 5, [6, [7, 8]]]; let flattenedArray = mixedArray.flat(Infinity); // Output: [1, 2, 3, 4, 5, 6, 7, 8] console.log(flattenedArray);
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
69 | 79 | 62 | 56 | 12 |