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;
}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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.