AniUI Academy

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 nested
flatten([1, [2, [3]]], Infinity);
// [1, 2, 3] — fully flat

Pass 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 + concat is the clean recursive form; a while-loop with an explicit stack avoids blowing the call stack on very deeply nested input.
Asked atMetaAmazonGoogle
Try it yourself
Loading playground...
3 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.