Skip to the code
cf.
+10 XP

#743 Flatten a List to a Depth

easy

Write your own version of Array.prototype.flat. flatten(items, depth) returns a new array where nested arrays are opened up to depth levels deep: arrays inside items are replaced by their items, arrays inside those are opened too while levels remain, and arrays deeper than depth are kept as they are.

depth = 0 returns a shallow copy. Non-array values (numbers, strings, objects, null) are never opened.

Example 1

Input: items = [1,[2,[3,[4]]],5], depth = 2
Output: [1,2,3,[4],5]

Two levels are opened, so [4], three levels deep, stays an array.

Example 2

Input: items = [1,[2,[3]]], depth = 1
Output: [1,2,[3]]

Only the first level is opened.

Constraints

  • items has at most 10^4 values in total; nesting is at most 100 levels.
  • 0 <= depth <= 100
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).