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.
β Simple Recursive 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; }
π Example
flattenRecursive([1, [2, [3, 4], 5], 6]); // β [1, 2, 3, 4, 5, 6]
π§ Atom-of-Thoughts Breakdown
-
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
resultarray to collect all flattened items.
π§ͺ Handles:
- Arbitrary nesting: β
- Mixed types: β
- Empty arrays: β
Hereβs a spec-compliant polyfill for Array.prototype.flat , matching ECMAScript behavior:
β Flat Polyfill (Depth-Aware)
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; }; }
π Usage
[1, [2, [3, [4]]]].flat(2); // β [1, 2, 3, [4]]
π§ Atom-of-Thoughts Breakdown
- Default
depth = 1for single-level flattening. - Recursive helper
flatten(arr, d):
- If item is array and
depth > 0β recurse withdepth - 1. - Else β push item to result.
- Uses closure
result[]to accumulate flattened values.
π§ͺ Edge Case Behavior
| 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