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

Array.prototype.flat() β€” flatten two levels

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

Pass a depth number to flat() to control how many nesting levels are flattened.

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

You can specify a numeric depth to control how many levels are unwrapped. flat(2) flattens two levels.

Challenge: Implement flatTwo(arr) that flattens exactly two levels using arr.flat(2).

flatTwo([1, [2, [3, [4]]]]) // β†’ [1, 2, 3, [4]]
flatTwo([[1], [[2, 3]]])    // β†’ [1, 2, 3]
πŸ’‘ Hints (2)
  • β€’ `flat(2)` unwraps arrays inside arrays, but leaves third-level nesting intact.
  • β€’ Depth 2 means: flatten once, then flatten the result once more.