Recursively: walk the array, and replace each element that is itself an array with its flattened contents. The usual follow-up is without recursion: use a stack, pop an item, push its children if it's an array, otherwise add it to the output. Popping visits items last-first, so reverse the result once at the end. Carry a remaining depth with each item to support flatten(xs, depth). Mention arr.flat(Infinity), the built-in, and for a strong finish a lazy generator that flattens any iterable but leaves strings whole (they're iterable too, and recursing into them never ends).
Flatten a nested array.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Walk the array. An element that is an array is replaced by its own flattened contents, and anything else is kept as is. It's correct and short, and it's what to write first. It creates a new array and leaves the input alone. Recursion depth equals nesting depth, which is what the follow-up targets.
// Recursion: an array is replaced by its flattened contents; anything else is kept.function flatten(arr) {const out = [];for (const item of arr) {if (Array.isArray(item)) out.push(...flatten(item));else out.push(item);}return out;}
passes 3 checks run on every build, against the native method where there is one
- flattens every level
- same as native flat(Infinity)
- the input isn't changed
Push the items onto a stack. Pop one: if it's an array (and depth remains), push its items, otherwise add it to the output. Popping from the end visits items in reverse, so build the output backwards and reverse once at the end, which is O(n) overall. Each stack item carries its remaining depth, so flatten(xs, 1) matches flat(1). It's compared with native flat on 200 random nestings, and it handles 100,000 levels.
// The follow-up "without recursion": a stack. Popping from the end visits items last-first,// so the output is built backwards and reversed once at the end. Depth is optional, like flat().function flatten(arr, depth = Infinity) {const out = [];const stack = [];const pushAll = (array, d) => {for (let i = 0; i < array.length; i++) if (i in array) stack.push([array[i], d]); // holes are skipped, as flat() does};pushAll(arr, depth);while (stack.length) {const [item, d] = stack.pop();if (Array.isArray(item) && d > 0) pushAll(item, d - 1);else out.push(item);}return out.reverse();}
passes 3 checks run on every build, against the native method where there is one
- matches native flat on 200 random nestings, at several depths
- no recursion: 100,000 levels deep
- holes are skipped, like flat()
A generator with a stack of iterators yields each value as soon as it's found and keeps the order. It flattens Sets and generators as well as arrays, and a consumer that stops early never reads the rest, even from an infinite source. Treat strings as values: a one-character string is itself iterable, so recursing into strings never ends. In everyday code, arr.flat(Infinity) is the answer for arrays.
// Lazy, and for any iterable: a generator that yields values as they're found, so a consumer that// stops early never touches the rest (it even works on infinite generators). Strings are// iterable too, but they're primitives here, so they stay whole instead of recursing forever.const isNested = (v) => v !== null && typeof v === 'object' && typeof v[Symbol.iterator] === 'function';function* flatten(iterable, depth = Infinity) {const stack = [{ it: iterable[Symbol.iterator](), depth }];while (stack.length) {const top = stack[stack.length - 1];const { value, done } = top.it.next();if (done) stack.pop();else if (top.depth > 0 && isNested(value)) stack.push({ it: value[Symbol.iterator](), depth: top.depth - 1 });else yield value;}}
passes 4 checks run on every build, against the native method where there is one
- arrays, Sets and generators
- strings stay whole
- lazy: takes from an infinite generator
- depth limit, and the same result as flat() on arrays
Array.prototype.flat
Since ES2019, flat(depth) does this natively (depth defaults to 1) and flatMap maps and flattens one level in one pass.
Nested children in UI trees
React accepts nested arrays as children and flattens them while rendering, which is why {items.map(...)} can sit next to other children.
Lazy iteration
Iterator helpers (Iterator.prototype.flatMap) bring the generator approach to the language: lazy, one value at a time.
Recursion on deeply nested, untrusted data (stack overflow).
[].concat(...arr)in a loop: flattens only one level per pass and is O(n·depth).Treating strings as nested iterables, which recurses forever.
Popping from a stack without reversing, which returns the items backwards.
toString().split(','), which turns numbers into strings and breaks on commas.
What's the complexity?
O(n) time for n total elements and sub-arrays, O(depth) extra space for the recursive version, and O(n) for the stack version's worst case.
How would you flatten objects instead?
That's "squash object": recurse into plain objects and join keys with dots. There's a separate answer in the bank.
What does flat() do with holes?
It removes them at every level it flattens. [1, , 3].flat() is [1, 3].