Deep Flatten Nested Arrays Without Recursion

Flatten arbitrarily nested arrays with an explicit stack and optional depth limit, avoiding call-stack overflow on deep input.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
export function flattenDeep(input, depth = Infinity) {
  if (!Array.isArray(input)) throw new TypeError("input must be an array");
  if (depth !== Infinity && (!Number.isInteger(depth) || depth < 0)) {
    throw new RangeError("depth must be a non-negative integer or Infinity");
  }
  const output = [];
  const stack = [];
  for (let index = input.length - 1; index >= 0; index -= 1) {
    stack.push({ value: input[index], level: 1 });
  }
  while (stack.length > 0) {
    const entry = stack.pop();
    if (Array.isArray(entry.value) && entry.level <= depth) {
      for (let index = entry.value.length - 1; index >= 0; index -= 1) {
        stack.push({ value: entry.value[index], level: entry.level + 1 });
      }
    } else {
      output.push(entry.value);
    }
  }
  return output;
}

Inside the snippet

Count the function flattenDeep as the entire surface area of Deep Flatten Nested Arrays Without Recursion.

The core work runs in nested loops — outer for (let index = input.length - 1; index >= 0; index -= 1), inner while (stack.length > 0). Instead of silently continuing, the code raises TypeError and RangeError at the guard.

Putting it to use

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

Treat flattenDeep as the API: import it, and ignore the supporting code.

Core lines

if (!Array.isArray(input)) throw new TypeError("input must be an array");
throw new RangeError("depth must be a non-negative integer or Infinity");

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
The code refuses to continue: `TypeError` and `RangeError` is thrown while the state is still recoverable.
Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `flattenDeep` at load time.