JS Built-ins
← Array88 / 226
ArrayArray.prototype.flatintermediate

Array.prototype.flat() β€” flatten to any depth

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

Pass Infinity to flat() to fully flatten an arbitrarily deeply nested array.

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

Passing Infinity as the depth argument to flat() flattens all levels of nesting, no matter how deep.

Challenge: Implement flatDeep(arr) that flattens all nested arrays using arr.flat(Infinity).

flatDeep([1, [2, [3, [4]]]]) // β†’ [1, 2, 3, 4]
flatDeep([[[[1]]]])           // β†’ [1]
πŸ’‘ Hints (2)
  • β€’ `Infinity` as the depth argument tells `flat()` to keep unwrapping until no nested arrays remain.
  • β€’ This is equivalent to repeatedly calling `flat()` until the array stops changing.