JavaScript Program to Flatten Nested Array Using Recursion
function flatten(arr) { return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []); } which checks each element and flattens nested arrays recursively.Examples
How to Think About It
Algorithm
Code
function flatten(arr) { return arr.reduce((acc, val) => { if (Array.isArray(val)) { return acc.concat(flatten(val)); } else { return acc.concat(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], acc = []
Process first element 1
1 is not an array, acc = [].concat(1) = [1]
Process second element [2, [3, 4], 5]
It is an array, call flatten([2, [3, 4], 5])
Inside recursive call flatten([2, [3, 4], 5])
Process 2 (not array), then [3,4] (array), then 5 (not array), result = [2, 3, 4, 5]
Back to first call, acc = [1].concat([2, 3, 4, 5]) = [1, 2, 3, 4, 5]
Process last element 6
6 is not an array, acc = [1, 2, 3, 4, 5].concat(6) = [1, 2, 3, 4, 5, 6]
Return final flattened array
[1, 2, 3, 4, 5, 6]
| Step | Accumulator (acc) |
|---|---|
| Start | [] |
| Add 1 | [1] |
| Flatten [2, [3,4], 5] | [1, 2, 3, 4, 5] |
| Add 6 | [1, 2, 3, 4, 5, 6] |
Why This Works
Step 1: Check each element
The function looks at each element to see if it is an array using Array.isArray().
Step 2: Use recursion for nested arrays
If an element is an array, the function calls itself on that element to flatten it further.
Step 3: Combine results
The results from recursive calls and simple elements are combined using concat to build the final 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, including nested ones, so time grows linearly with total elements.
Space Complexity
Extra space is used for the output array and the call stack during recursion, both proportional to the number of elements.
Which Approach is Fastest?
The built-in flat(Infinity) method is fastest and simplest but requires modern JS. Recursive and iterative methods have similar performance but differ in readability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive flatten | O(n) | O(n) | Understanding recursion and nested structures |
| Array.flat(Infinity) | O(n) | O(n) | Quick and simple with modern JS |
| Iterative stack flatten | O(n) | O(n) | Avoiding recursion for deep nesting |