CodePark/ problems / Flatten to a depth
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Array and collection utilities

Flatten to a depth

hardabout 30 minutes in an interview

Implement flatten(arr, depth = 1), which behaves like arr.flat(depth). Don't call Array.prototype.flat or flatMap.

It returns a new array in which nested arrays are unwrapped up to depth levels. Unwrapping means the items of a nested array take the place of the array itself.

  • depth defaults to 1. Infinity unwraps everything. 0 or a negative depth unwraps nothing and returns a shallow copy.
  • The order of items is kept. An empty nested array that gets unwrapped leaves nothing behind.
  • Holes in sparse arrays (indexes never assigned, as in [1, , 2]) are dropped in every array that gets unwrapped. Real undefined and null values are kept.
  • Don't modify the input.

Constraints: up to 200 000 items in total, and arrays may be nested up to 100 000 levels deep.

Input: flatten([1, [2, [3, [4]]], 5]) Output: [1, 2, [3, [4]], 5]
Input: flatten([1, [2, [3, [4]]]], 2) Output: [1, 2, 3, [4]]
Input: flatten([[], ['a'], [[], 'b']], Infinity) Output: ['a', 'b']