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.
Code
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;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.