Array Flattening with Depth
easyArrays & Objects+150 XPFrontend AlgoArena
Nested arrays show up all the time — JSON responses, tree walks, grouped selections. Array.prototype.flat exists, but writing it yourself is a staple interview question.
Implement flatten(arr, depth) that returns a new array where sub-arrays are inlined up to depth levels deep. Elements beyond that depth stay nested.
Arguments
arrArray<unknown>- The array to flatten.
depthnumber- How many levels of nesting to collapse. Defaults to 1.
Returns
Array<unknown> — A new array with sub-arrays inlined up to the given depth.
Examples
flatten([1, [2, [3]], 4]);
// [1, 2, [3], 4] — default depth of 1
flatten([1, [2, [3, [4]]]], 2);
// [1, 2, 3, [4]] — the [4] stays nestedflatten([1, [2, [3]]], Infinity);
// [1, 2, 3] — fully flatPass Infinity to collapse every level, matching Array.prototype.flat(Infinity).
What it has to do
- Recursively flatten sub-arrays up to
depth. - Default depth should be 1 if not specified.
- Do not mutate original array.
Notes
reduce+concatis the clean recursive form; awhile-loop with an explicit stack avoids blowing the call stack on very deeply nested input.
Try it yourself· Edit the code, then press Run
Loading playground...
- 1.flattens single level by default
- 2.flattens up to specified depth
- 3.handles empty array
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
3 tests · +150 XP
Discussion
Sign in to postSign in to join the conversation.Sign in
No comments yet. Be the first to say something.