Flatten a nested array
Use arr.flat(Infinity) in practice; in interviews, implement it recursively (concatenating flattened sub-arrays) or iteratively with an explicit stack to avoid recursion limits on deeply nested input.
Recursive solution
For each element: if it is an array, flatten it and spread the result; otherwise push it. Support a depth parameter to mirror Array.prototype.flat.
Iterative solution (stack)
Push the input onto a stack in reverse; pop items; if an item is an array, push its elements back (in reverse to keep order); otherwise add it to the result. This handles any depth without risking a stack overflow and is a good follow-up answer.
Generator solution
function* flatten(arr) { for (const x of arr) Array.isArray(x) ? yield* flatten(x) : yield x } flattens lazily, useful for huge or streamed data.
Details to mention
Array.isArrayis the right check (strings are iterable but should not be split).flatremoves holes in sparse arrays; decide whether your version should too.- Complexity: O(n) over the total number of elements, O(d) recursion depth or O(n) stack space.
- Avoid repeated
concatin a loop (result = result.concat(...)), which copies the array each time and becomes O(n²).
Code example
1// 1. Recursive with an optional depth (like Array.prototype.flat)2function flatten(arr, depth = Infinity) {3 const out = [];4 for (const item of arr) {5 if (Array.isArray(item) && depth > 0) out.push(...flatten(item, depth - 1));6 else out.push(item);7 }8 return out;9}1011// 2. Iterative with an explicit stack: no recursion limits12function flattenIterative(arr) {13 const stack = [...arr].reverse();14 const out = [];15 while (stack.length) {16 const item = stack.pop();17 if (Array.isArray(item)) for (let i = item.length - 1; i >= 0; i--) stack.push(item[i]);18 else out.push(item);19 }20 return out;21}2223// 3. Lazy generator24function* flattenLazy(arr) {25 for (const item of arr) Array.isArray(item) ? yield* flattenLazy(item) : yield item;26}2728const nested = [1, [2, [3, [4, [5]]]], "six", [[["seven"]]]];29console.log(flatten(nested)); // [1, 2, 3, 4, 5, "six", "seven"]30console.log(flatten(nested, 1)); // [1, 2, [3, [4, [5]]], "six", [["seven"]]]31console.log(flattenIterative(nested)); // [1, 2, 3, 4, 5, "six", "seven"]32console.log([...flattenLazy(nested)].join()); // 1,2,3,4,5,six,seven33console.log(JSON.stringify(flatten(nested)) === JSON.stringify(nested.flat(Infinity))); // true3435// Very deep nesting: the iterative version survives36let deep = [0];37for (let i = 1; i <= 50_000; i++) deep = [deep, i];38console.log(flattenIterative(deep).length); // 50001
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.