How do you flatten a nested array in JavaScript without using flat()?
Quick answer
Recursively walk the array: when an element is an array, flatten it and append the result; otherwise append the element. An iterative version uses an explicit stack to avoid recursion limits.
Problem
Write a function that takes an array that may contain nested arrays to any depth and returns a new, single-level array with all the values in their original order.
Input
Output
Constraints
- Do not use Array.prototype.flat
- Preserve the original order
Example
The nested values 2, 3, 4 and 5 are lifted to the top level in the order they appear.
Solution
function flatten(arr) {
const result = [];
for (const item of arr) {
if (Array.isArray(item)) {
result.push(...flatten(item));
} else {
result.push(item);
}
}
return result;
}
flatten([1, [2, [3, [4]], 5]]); // [1, 2, 3, 4, 5]Loop through each item of the input array.
If the item is an array, flatten it recursively and push its values.
Otherwise push the item itself.
Return the collected result.
Time complexity
Space complexity
Alternative approach
An iterative version uses a stack, which avoids recursion limits for very deep arrays. Pop from the end, push nested arrays back, and reverse at the end to restore the order.
function flattenIterative(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const item = stack.pop();
if (Array.isArray(item)) stack.push(...item);
else result.push(item);
}
return result.reverse();
}Discussion
In real code arr.flat(Infinity) does this, and you should say so. Interviewers ask you to write it yourself to see recursion, Array.isArray and how you reason about depth.
The recursive solution mirrors the structure of the data and is easy to explain. For very deep nesting it can hit the call-stack limit, so mentioning an iterative stack-based version is a good follow-up.
Common mistakes
- Using typeof item === "object" to detect arrays, which also matches objects and null.
- Mutating the input array.
Follow-up questions
- How would you flatten only to a given depth?