JavaScript Program to Flatten Deeply Nested Array
function flatten(arr) { return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []); } to flatten deeply nested arrays in JavaScript.Examples
How to Think About It
Algorithm
Code
function flatten(arr) { return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []); } const nestedArray = [1, [2, [3, 4], 5], 6]; console.log(flatten(nestedArray));
Dry Run
Let's trace [1, [2, [3, 4], 5], 6] through the code
Start with full array
arr = [1, [2, [3, 4], 5], 6]
Process first element 1
1 is not an array, add 1 to acc
Process second element [2, [3, 4], 5]
It is an array, call flatten recursively
Inside recursive call for [2, [3, 4], 5]
Flatten to [2, 3, 4, 5]
Add flattened result [2, 3, 4, 5] to acc
acc = [1, 2, 3, 4, 5]
Process third element 6
6 is not an array, add 6 to acc
Final result
acc = [1, 2, 3, 4, 5, 6]
| Step | Current Element | Is Array? | Accumulator |
|---|---|---|---|
| 1 | 1 | No | [1] |
| 2 | [2, [3, 4], 5] | Yes | [1, 2, 3, 4, 5] |
| 3 | 6 | No | [1, 2, 3, 4, 5, 6] |
Why This Works
Step 1: Check each element
The function looks at each item in the array to decide if it needs to go deeper or just keep the value.
Step 2: Use recursion for nested arrays
If an element is an array, the function calls itself to flatten that smaller array first.
Step 3: Combine results
All flattened parts are combined using concat to build one flat array.
Alternative Approaches
const flattened = nestedArray.flat(Infinity); console.log(flattened);
function flattenIterative(arr) { const stack = [...arr]; const result = []; while (stack.length) { const next = stack.pop(); if (Array.isArray(next)) { stack.push(...next); } else { result.push(next); } } return result.reverse(); } console.log(flattenIterative([1, [2, [3, 4], 5], 6]));
Complexity: O(n) time, O(n) space
Time Complexity
The function visits each element once, so time grows linearly with the total number of elements including nested ones.
Space Complexity
Extra space is needed to store the flattened array and the call stack during recursion, both proportional to the total elements.
Which Approach is Fastest?
Using flat(Infinity) is fastest and simplest in modern JavaScript, recursion is clear but slower, iterative stack avoids recursion overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive flatten | O(n) | O(n) | Clear logic, moderate depth |
| Array.flat(Infinity) | O(n) | O(n) | Modern environments, simplest code |
| Iterative stack | O(n) | O(n) | Very deep arrays, avoid recursion limits |
Array.flat(Infinity) for the easiest flattening if your environment supports it.