DEV Community

Souvik Guha Roy
Souvik Guha Roy

Posted on

Array Flatten in JavaScript

Working with arrays is common in JavaScript—but sometimes arrays can get nested, making them harder to use. That’s where array flattening comes in.

In this blog, we’ll break down what nested arrays are, why flattening is useful, and explore different ways to flatten arrays step by step.


📦 What Are Nested Arrays?

A nested array is simply an array inside another array.

Example:

```js id="ex1"
const arr = [1, 2, [3, 4], [5, [6, 7]]];




Here:

* `[3, 4]` is a nested array
* `[5, [6, 7]]` is **deeply nested**

---

## 🧠 Visual Representation

### Nested Structure:



```id="viz1"
[ 
  1,
  2,
  [3, 4],
  [5, [6, 7]]
]
Enter fullscreen mode Exit fullscreen mode

Think of it like layers:

Level 1 → 1, 2
Level 2 → 3, 4, 5
Level 3 → 6, 7
Enter fullscreen mode Exit fullscreen mode

❓ Why Flattening Arrays Is Useful

Flattening converts a nested array into a single-level array.

Example:

```js id="ex2"
Input: [1, 2, [3, 4], [5, [6, 7]]]
Output: [1, 2, 3, 4, 5, 6, 7]




### 💡 Use Cases:

* API responses with nested data
* Data processing & transformation
* Simplifying loops and operations
* Preparing data for UI rendering

---

## 🔄 Concept of Flattening Arrays

Flattening means:

> “Take elements from all nested levels and bring them into one level.”

---

## 🛠️ Different Approaches to Flatten Arrays

---

### 1. Using `flat()` (Built-in Method)

The easiest way in modern JavaScript.



```js id="code1"
const arr = [1, 2, [3, 4], [5, [6, 7]]];

const flatArr = arr.flat(2);

console.log(flatArr);
// [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

📝 Notes:

  • flat(depth) defines how deep to flatten
  • Use Infinity for full flattening

```js id="code2"
arr.flat(Infinity);




---

### 2. Using Recursion (Most Important for Interviews)

This is the **classic interview approach**.



```js id="code3"
function flattenArray(arr) {
  let result = [];

  for (let item of arr) {
    if (Array.isArray(item)) {
      result = result.concat(flattenArray(item));
    } else {
      result.push(item);
    }
  }

  return result;
}

console.log(flattenArray([1, [2, [3, 4]], 5]));
Enter fullscreen mode Exit fullscreen mode

🔍 Step-by-Step Thinking

  1. Loop through array
  2. Check:
  • If element is array → flatten again
  • Else → push to result
    1. Combine results

3. Using reduce()

A functional approach:

```js id="code4"
const flattenArray = (arr) =>
arr.reduce((acc, curr) => {
return acc.concat(
Array.isArray(curr) ? flattenArray(curr) : curr
);
}, []);

console.log(flattenArray([1, [2, [3]], 4]));




---

### 4. Using Stack (Iterative Approach)

Avoids recursion:



```js id="code5"
function flattenArray(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();
}
Enter fullscreen mode Exit fullscreen mode

📊 Flatten Transformation Visual

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

Step 1 → [1, 2, [3, 4], 5]
Step 2 → [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

🎯 Common Interview Scenarios

1. Flatten to Specific Depth

```js id="code6"
function flattenDepth(arr, depth) {
if (depth === 0) return arr;

return arr.reduce((acc, curr) => {
if (Array.isArray(curr)) {
acc.push(...flattenDepth(curr, depth - 1));
} else {
acc.push(curr);
}
return acc;
}, []);
}




---

### 2. Infinite Flatten



```js id="code7"
flattenArray(arr); // recursive solution
Enter fullscreen mode Exit fullscreen mode

3. Edge Cases Interviewers Test

  • Empty array → []
  • No nesting → same array
  • Deep nesting → performance check

🧩 Problem-Solving Mindset

When solving flatten problems, think:

  • ✔ Is recursion needed?
  • ✔ Can I reduce complexity?
  • ✔ What is the depth?
  • ✔ Should I preserve order?

🚀 Final Thoughts

Array flattening is a must-know concept in JavaScript because it:

  • Strengthens recursion skills
  • Improves problem-solving ability
  • Appears frequently in interviews

Start with flat() for real projects, but master recursion for interviews.


Top comments (0)