Flatten a Nested Array to a Depth

Flatten arrays nested to an arbitrary depth into a single level, with an optional depth limit so callers can control how far the flattening goes.

JavascriptData Integrity

Code

javascriptsnippet
14 lines
export function flatten(input, depth = Infinity) {
  const output = [];
  const walk = (items, remaining) => {
    for (const item of items) {
      if (Array.isArray(item) && remaining > 0) {
        walk(item, remaining - 1);
      } else {
        output.push(item);
      }
    }
  };
  walk(input, depth);
  return output;
}

How the snippet works

The working surface is the functions walk and flatten — everything else is wiring.

The loop for (const item of items) is the only repeated construct.

Applying it

The primary signature is export function flatten(input, depth = Infinity)

flatten is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

const walk = (items, remaining) => {
  for (const item of items) {
    if (Array.isArray(item) && remaining > 0) {
      walk(item, remaining - 1);
    } else {
      output.push(item);
    }
  }
};

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. The file defines `walk`, `flatten` at load time.