JS Built-ins
← Array87 / 226
ArrayArray.prototype.flatbeginner

Array.prototype.flat() β€” flatten one level

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

Use flat() with no arguments to flatten one level of nested arrays.

Array.prototype.flat()

Array.prototype.flat(depth?) returns a new array with all sub-array elements concatenated recursively up to the specified depth (default: 1). It does not mutate the original array.

Challenge: Implement flatOnce(arr) that flattens one level deep using .flat().

flatOnce([1, [2, 3], [4, [5]]]) // β†’ [1, 2, 3, 4, [5]]
flatOnce([[1], [2, 3]])         // β†’ [1, 2, 3]
πŸ’‘ Hints (2)
  • β€’ `flat()` with no argument defaults to depth `1`.
  • β€’ Nested arrays deeper than depth 1 are not unwrapped.