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

snippet
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;
}