The JavaScript Array flat() method is used to flatten an array by reducing the nesting of sub-arrays into a single array. It returns a new array with all the sub-array elements concatenated into it recursively up to a specified depth. By default, the method flattens the array to a depth of 1.
For example, array.flat(depth) is useful when you need to convert a nested array structure into a single-level array.
Syntax
The syntax for the Array.flat() method is:
array.flat(depth)
Parameters
The Array.flat() method accepts one optional parameter:
- depth (Optional): The depth level specifying how deep the flattening should go. The default value is 1.
Return Value
A new array with the sub-array elements concatenated into it, flattened according to the specified depth.
Examples of JavaScript Array.flat() Method
Example 1: Flattening a Nested Array
The default behavior of flat() flattens the array by 1 level.
const arr = [1, 2, [3, 4]];
const flatArray = arr.flat();
console.log(flatArray); // Output: [1, 2, 3, 4]
Explanation: The flat() method flattens the nested array [3, 4] by one level, returning a new array [1, 2, 3, 4].
Example 2: Specifying a Depth to Flatten
You can specify a depth to control how deeply the array should be flattened.
const arr = [1, 2, [3, 4, [5, 6]]];
const flatArray = arr.flat(2);
console.log(flatArray); // Output: [1, 2, 3, 4, 5, 6]
Explanation: The flat(2) method flattens the array two levels deep, so the nested array [5, 6] is also flattened, resulting in a fully flattened array.
Example 3: Flattening an Array with Default Depth
When no depth is specified, the flat() method uses the default depth of 1.
const arr = [1, 2, [3, 4, [5, 6]]];
const flatArray = arr.flat();
console.log(flatArray); // Output: [1, 2, 3, 4, [5, 6]]
Explanation: Since no depth is specified, the array is flattened by 1 level, leaving [5, 6] still nested.
Example 4: Flattening an Array with Infinite Depth
To flatten all levels of a deeply nested array, you can specify Infinity as the depth.
const arr = [1, 2, [3, 4, [5, 6, [7, 8]]]];
const flatArray = arr.flat(Infinity);
console.log(flatArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8]
Explanation: The flat(Infinity) method flattens the array to all levels, returning a fully flattened array [1, 2, 3, 4, 5, 6, 7, 8].
Example 5: Flattening an Array with Empty Slots
The flat() method removes empty slots in arrays, treating them as undefined.
const arr = [1, 2, , 4, [5, , 7]];
const flatArray = arr.flat();
console.log(flatArray); // Output: [1, 2, 4, 5, 7]
Explanation: The flat() method removes empty slots (,) in both the main array and sub-arrays, resulting in a new array [1, 2, 4, 5, 7].