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