Flatten a nested array (recursion)
Medium TimeO(n) total elements SpaceO(d) depth
An array can hold plain values or other arrays, nested to any depth. Given one, return a single flat array holding every value in its original left-to-right order, so [1, [2, [3, 4]], 5] becomes [1, 2, 3, 4, 5]. Empty arrays contribute nothing.
Examples
Example 1
- Input
- arr = [1, [2, [3, 4]], 5]
- Output
- The same five values in the same order, with the brackets gone.
[1,2,3,4,5]
Example 2
- Input
- arr = [[], [1, []], 2]
- Output
- Only
[1,2]1and2are values; the two empty arrays add nothing.
The Code
function flatten(arr) {
const out = [];
for (const item of arr) {
if (Array.isArray(item)) {
for (const x of flatten(item)) out.push(x);
} else {
out.push(item);
}
}
return out;
}
flatten([1, [2, [3, 4]], 5]);Done
More like this
All recursion examples (13) →- Fibonacci The classic branching recursion — every call spawns two more.
- Factorial The simplest linear recursion — one call, one multiply.
- Tower of Hanoi Move a stack of disks by trusting the recursion for the rest.
- GCD (Euclid) Euclid’s algorithm — recursion that shrinks fast.
- Power Raise a number to a power one multiply at a time.
- Sum of digits Peel one digit off at a time with the modulo trick.