HomePremium · ₹1199
← All questions

Flatten an array

Easy
Asked at:AmazonAdobe
Was this asked in an interview?

Flatten an arbitrarily nested array to a given depth — your own Array.prototype.flat.

Problem

Implement flatten(arr, depth = Infinity) — your own version of Array.prototype.flat.

Nested arrays show up everywhere: a tree of comments, grouped API results, or config merged from several sources. You need to collapse that nesting into a single-level array, but only down to a given depth so callers stay in control.

flatten(arr, depth) must:

  • Recursively flatten nested arrays up to depth levels (default: flatten completely).
  • Preserve element order.
  • Leave non-array elements untouched.
  • Return a new array (don't mutate the input).

Input

flatten([1, [2, [3, [4]]]]);      // depth defaults to Infinity
flatten([1, [2, [3]]], 1);        // only one level

Expected output

  • [1, 2, 3, 4]
  • [1, 2, [3]]

Implement from scratch (no Array.prototype.flat):

function flatten(arr, depth = Infinity) {
  // Your code here
}