coding round · ~10 min
JavaScriptbeginner

Flatten a nested array

Write flatten(arr, depth = Infinity) that returns a new array with nested arrays flattened up to depth levels deep, without using Array.prototype.flat.

  • flatten([1, [2, [3, [4]]]]) → [1, 2, 3, 4]
  • flatten([1, [2, [3, [4]]]], 1) → [1, 2, [3, [4]]]
  • flatten([[], [[]], 5]) → [5]
  • flatten([1, [2]], 0) → [1, [2]] (a shallow copy)

Only arrays get flattened: objects, strings and null stay as they are. Don't mutate the input.

Define flatten in the editor. 7 tests will call it.

solution.js
function flatten(arr, depth = Infinity) {
  // Return a new array where nested arrays are flattened
  // up to `depth` levels deep. Don't use Array.prototype.flat.
}

Tests⌘/Ctrl + Enter to run

flattens deeply nested arrays by default
flattens only one level when depth is 1
respects a depth of 2
depth 0 returns a shallow copy
drops empty arrays and keeps non-array values as they are
does not mutate the input
works without Array.prototype.flat
esc