0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Flatten Deeply Nested Array

Use a recursive function like function flatten(arr) { return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []); } to flatten deeply nested arrays in JavaScript.
📋

Examples

Input[1, 2, 3]
Output[1, 2, 3]
Input[1, [2, [3, 4], 5], 6]
Output[1, 2, 3, 4, 5, 6]
Input[[[[1]], 2], 3, [4, [5, [6]]]]
Output[1, 2, 3, 4, 5, 6]
🧠

How to Think About It

To flatten a deeply nested array, think about checking each item: if it's an array, break it down further by calling the same process on it; if it's not, keep it as is. This way, you keep going deeper until no arrays remain inside, collecting all values into one flat list.
📐

Algorithm

1
Get the input array.
2
Create an empty list to hold results.
3
For each element in the array:
4
Check if the element is an array.
5
If yes, flatten it recursively and add all its elements to the result list.
6
If no, add the element directly to the result list.
7
Return the result list.
💻

Code

javascript
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));
Output
[1, 2, 3, 4, 5, 6]
🔍

Dry Run

Let's trace [1, [2, [3, 4], 5], 6] through the code

1

Start with full array

arr = [1, [2, [3, 4], 5], 6]

2

Process first element 1

1 is not an array, add 1 to acc

3

Process second element [2, [3, 4], 5]

It is an array, call flatten recursively

4

Inside recursive call for [2, [3, 4], 5]

Flatten to [2, 3, 4, 5]

5

Add flattened result [2, 3, 4, 5] to acc

acc = [1, 2, 3, 4, 5]

6

Process third element 6

6 is not an array, add 6 to acc

7

Final result

acc = [1, 2, 3, 4, 5, 6]

StepCurrent ElementIs Array?Accumulator
11No[1]
2[2, [3, 4], 5]Yes[1, 2, 3, 4, 5]
36No[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

Using flat() method
javascript
const flattened = nestedArray.flat(Infinity);
console.log(flattened);
This is the simplest and fastest way in modern JavaScript but requires ES2019 support.
Iterative approach with stack
javascript
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]));
Uses a stack to avoid recursion, good for very deep arrays but code is more complex.

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.

ApproachTimeSpaceBest For
Recursive flattenO(n)O(n)Clear logic, moderate depth
Array.flat(Infinity)O(n)O(n)Modern environments, simplest code
Iterative stackO(n)O(n)Very deep arrays, avoid recursion limits
💡
Use Array.flat(Infinity) for the easiest flattening if your environment supports it.
⚠️
Forgetting to check if an element is an array before flattening causes errors or wrong results.