Array.prototype.flat Polyfill
ArraysPolyfill
Implement Array.prototype.myFlat(depth = 1).
Requirements:
- Default depth is 1 (not Infinity)
- Recursively flatten nested arrays, decrementing depth on each level
flat(Infinity)must fully flatten any nesting- Do not mutate the original array
Examples
Example 1
Input
[1, [2, [3, 4]]].myFlat()Output
[1, 2, [3, 4]]Explanation
Default depth of 1 flattens only one level.
Example 2
Input
[1, [2, [3, 4]]].myFlat(2)Output
[1, 2, 3, 4]Explanation
Depth 2 flattens both levels.
Example 3
Input
[1, [2, [3, [4, [5]]]]].myFlat(Infinity)Output
[1, 2, 3, 4, 5]Explanation
Infinity flattens completely.
Notes
- Pass `currentDepth - 1` into the recursive call — do not re-read the parameter
Hints
Editorial: Array.prototype.flat Polyfill
Implementing Array.prototype.flat from scratch
flat flattens nested arrays up to a given depth. The default depth is 1, not Infinity. flat(Infinity) flattens completely.
What the interviewer checks
- Do you default depth to 1?
- Do you correctly decrement the depth counter through recursion?
Recursive implementation
Array.prototype.myFlat = function (depth = 1) { const result = []; (function flatten(arr, currentDepth) { for (const item of arr) { if (Array.isArray(item) && currentDepth > 0) { flatten(item, currentDepth - 1); } else { result.push(item); } } })(this, depth); return result; };
Reduce-based one-liner (bonus)
Array.prototype.myFlat = function (depth = 1) { return this.reduce((acc, item) => { if (Array.isArray(item) && depth > 0) { return acc.concat(item.myFlat(depth - 1)); } return acc.concat(item); }, []); };
The recursive IIFE version is clearer in interviews. Mention the reduce version as an alternative.
How depth works
[1, [2, [3, 4]]].myFlat() // depth 1 → [1, 2, [3, 4]] [1, [2, [3, 4]]].myFlat(2) // depth 2 → [1, 2, 3, 4] [1, [2, [3, [4]]]].myFlat(Infinity) // fully → [1, 2, 3, 4]
Each level of recursion passes currentDepth - 1. When currentDepth reaches 0, nested arrays are pushed as-is.
Edge cases to mention
- Default depth is
1, notInfinity— this surprises people flat(0)returns a shallow copy with no flatteningflat(Infinity)works becauseInfinity - 1 === Infinity, so the depth never reaches 0- Does not skip holes:
[1, , 3].myFlat()→[1, 3](holes become absent in the result)
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it