JS Built-ins
← Array91 / 226
ArrayArray.prototype.flatadvanced

Array.prototype.flat() β€” configurable depth

πŸ“– Usage Example
const arr = [[1, 2], [3, [4, 5]]]
arr.flat(1)  // β†’ [1, 2, 3, [4, 5]]
arr.flat(2)  // β†’ [1, 2, 3, 4, 5]

Tune the depth argument of flat() to precisely control how many nesting levels collapse.

Array.prototype.flat() β€” dynamic depth

The depth argument to flat() can be any non-negative integer or Infinity. This lets you build configurable flattening utilities.

Challenge: Implement flatToDepth(arr, depth) that wraps arr.flat(depth).

flatToDepth([1, [2, [3]]], 1) // β†’ [1, 2, [3]]
flatToDepth([1, [2, [3]]], 2) // β†’ [1, 2, 3]
πŸ’‘ Hints (2)
  • β€’ Any non-negative integer works as the depth argument.
  • β€’ Depth `0` returns a shallow copy of the array without flattening.