0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Flatten Nested Array Using Recursion

You can flatten a nested array in JavaScript using recursion by defining a function like 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

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

How to Think About It

To flatten a nested array, think of going through each item one by one. If the item is a simple value, keep it. If the item is an array, open it up and flatten it too by calling the same process again. This way, you keep breaking down nested arrays until all values are simple and collected in one 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 it is an array.
5
If yes, call the flatten function on it and add all results to the list.
6
If no, add the element directly to the list.
7
Return the list with all elements flattened.
💻

Code

javascript
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));
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], acc = []

2

Process first element 1

1 is not an array, acc = [].concat(1) = [1]

3

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

It is an array, call flatten([2, [3, 4], 5])

4

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]

5

Back to first call, acc = [1].concat([2, 3, 4, 5]) = [1, 2, 3, 4, 5]

6

Process last element 6

6 is not an array, acc = [1, 2, 3, 4, 5].concat(6) = [1, 2, 3, 4, 5, 6]

7

Return final flattened array

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

StepAccumulator (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

Using flat() method
javascript
const flattened = nestedArray.flat(Infinity);
console.log(flattened);
This is simpler but requires modern JavaScript (ES2019+). It is not recursive code but built-in.
Using iterative stack approach
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]));
This avoids recursion by using a stack but is more complex to understand.

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.

ApproachTimeSpaceBest For
Recursive flattenO(n)O(n)Understanding recursion and nested structures
Array.flat(Infinity)O(n)O(n)Quick and simple with modern JS
Iterative stack flattenO(n)O(n)Avoiding recursion for deep nesting
💡
Use recursion to handle any depth of nested arrays by calling the function on sub-arrays.
⚠️
Forgetting to return the recursive call result or not concatenating arrays properly causes incorrect flattening.