The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. This polyfill provides both a simple recursive solution and a spec-compliant depth-aware implementation.
function flattenRecursive(arr) { let result = []; for (const item of arr) { if (Array.isArray(item)) { result = result.concat(flattenRecursive(item)); // recurse } else { result.push(item); // base case } } return result; }
flattenRecursive([1, [2, [3, 4], 5], 6]); // β [1, 2, 3, 4, 5, 6]
Base Case:
If the item is not an array , push it to the result.
Recursive Case:
If the item is an array , call flattenRecursive() on it, and concatenate its result.
Accumulator:
Uses a local result array to collect all flattened items.
Hereβs a spec-compliant polyfill for Array.prototype.flat , matching ECMAScript behavior:
if (!Array.prototype.flat) { Array.prototype.flat = function(depth = 1) { const result = []; (function flatten(arr, d) { for (const item of arr) { if (Array.isArray(item) && d > 0) { flatten(item, d - 1); } else { result.push(item); } } })(this, depth); return result; }; }
[1, [2, [3, [4]]]].flat(2); // β [1, 2, 3, [4]]
depth = 1 for single-level flattening.flatten(arr, d) :depth > 0 β recurse with depth - 1.result[] to accumulate flattened values.| Input | Output |
|---|---|
[1, 2, [3]] | [1, 2, 3] |
[1, [2, [3]]]with depth=1 | [1, 2, [3]] |
[1, [2, [3]]]with depth=2 | [1, 2, 3] |
[1, [2, [3]]]with depth=0 | [1, [2, [3]]] |
Test your understanding with 3 quick questions