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

Read the full write-up for Array.prototype.flat Polyfill
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it