Array.prototype.flatLoading saved progress…

Array.prototype.flat

Array.prototype.flat returns a new array with nested arrays pulled up into the parent, down to a depth you choose. It's how you turn [1, [2, 3]] into [1, 2, 3], or collapse an arbitrarily deep tree in one call.

Implement arrayFlat(arr, depth). Flatten nested arrays up to depth levels deep. depth defaults to 1; pass Infinity to flatten completely. Like the real method, it drops holes and returns a new array without mutating the input.

Signature

function arrayFlat(arr, depth = 1) {
  // returns a new array with sub-arrays flattened up to `depth` levels.
}

Examples

arrayFlat([1, [2, 3], 4]);        // [1, 2, 3, 4]  — one level by default
arrayFlat([1, [2, [3]]]);         // [1, 2, [3]]   — deeper nesting stays
arrayFlat([1, [2, [3, [4]]]], 2);        // [1, 2, 3, [4]]
arrayFlat([1, [2, [3, [4]]]], Infinity); // [1, 2, 3, 4]

Notes

  • Default depth is 1 — only the outermost level of nesting is flattened unless you ask for more.
  • Infinity — flattens every level, no matter how deep.
  • depth of 0 — no flattening; returns a shallow copy of the input.
  • Holes are dropped — a sparse [1, , 3] flattens to [1, 3].
  • Don't mutate — return a new array; leave the input untouched.
Loading editor…