How Array.prototype.flat Handles Nested Arrays
The Array.prototype.flat() method in JavaScript provides
a built-in mechanism to concatenate sub-array elements into a single,
new array. This article explains how the method processes nested arrays
of various depths, how to completely flatten arbitrarily deep structures
using Infinity, how it handles empty array slots, and its
non-mutating nature.
Basic Syntax and Default Behavior
The flat() method creates a new array with all sub-array
elements concatenated into it recursively up to a specified depth.
const newArray = array.flat([depth]);By default, the depth parameter is set to
1. If no argument is provided, only the first level of
nested arrays is unpacked.
const nestedArray = [1, 2, [3, 4], [5, 6]];
const flattened = nestedArray.flat();
console.log(flattened);
// Output: [1, 2, 3, 4, 5, 6]Specifying Depth Levels
When working with multi-level nested arrays, you can pass an integer greater than 1 to determine how many levels should be unwrapped.
const deeplyNested = [1, [2, [3, [4]]]];
// Flatten 1 level (default)
console.log(deeplyNested.flat(1));
// Output: [1, 2, [3, [4]]]
// Flatten 2 levels
console.log(deeplyNested.flat(2));
// Output: [1, 2, 3, [4]]Flattening Arbitrarily Deep Arrays with Infinity
If the nesting depth of an array is unknown or varies dynamically,
you can pass Infinity as the depth argument. This will
recursively flatten all nested structures until a fully one-dimensional
array is produced.
const chaoticArray = [1, [2, [3, [4, [5, [6]]]]]];
const fullyFlat = chaoticArray.flat(Infinity);
console.log(fullyFlat);
// Output: [1, 2, 3, 4, 5, 6]Handling Sparse Arrays (Empty Slots)
The flat() method automatically removes empty slots
(sparse elements) from an array during execution.
const sparseArray = [1, 2, , 4, [5, , 7]];
const cleanedArray = sparseArray.flat();
console.log(cleanedArray);
// Output: [1, 2, 4, 5, 7]Immutability
The flat() method is non-mutating. It returns a shallow
copy containing the flattened values while leaving the original source
array intact.
const original = [1, [2, 3]];
const modified = original.flat();
console.log(original);
// Output: [1, [2, 3]] (unchanged)
console.log(modified);
// Output: [1, 2, 3]