# Array Flatten in JavaScript

Modern JavaScript applications work with data everywhere. APIs, databases, user inputs, and UI components often return data in nested structures. Because of this, understanding how to flatten arrays is an important skill for every JavaScript developer.

Flattening arrays is also a common interview topic because it tests problem solving, recursion, loops, and understanding of array methods.

In this blog, you will learn:

*   What nested arrays are
    
*   Why flattening arrays is useful
    
*   The concept of flattening
    
*   Multiple approaches to flatten arrays
    
*   Common interview scenarios
    
*   Step by step thinking process
    

* * *

## What Are Nested Arrays?

A nested array is simply an array that contains another array inside it.

Example:

```js
const arr = [1, 2, [3, 4]];
```

Here:

*   `1` and `2` are normal elements
    
*   `[3, 4]` is another array inside the main array
    

More deeply nested example:

```js
const arr = [1, [2, [3, [4, 5]]]];
```

Visual representation:

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

![](https://cdn.hashnode.com/uploads/covers/695a275cee3d7756437f49db/2b5ea9c1-97c4-424d-a915-acaa4ffa4d13.png align="center")

## What Does Flattening Mean?

Flattening means converting a nested array into a single-level array.

Example:

```js
const arr = [1, [2, 3], [4, 5]];
```

Flattened version:

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

Deep nested flattening:

```js
const arr = [1, [2, [3, [4]]]];
```

Result:

```js
[1, 2, 3, 4]
```

* * *

## Why Is Flattening Arrays Useful?

Flattening arrays is useful in many real-world situations.

### 1\. API Data Processing

Sometimes APIs return nested data structures.

Example:

```js
const users = [
  ["Aslam", "John"],
  ["Sara", "Mike"]
];
```

Flattening helps create one clean list:

```js
["Aslam", "John", "Sara", "Mike"]
```

* * *

### 2\. UI Rendering

Frontend frameworks often need flat arrays for rendering lists.

Example:

```js
products.map(product => ...)
```

If products are nested, flattening simplifies rendering.

* * *

### 3\. Data Analysis

Data manipulation becomes easier when everything is in one level.

* * *

## Understanding the Flattening Process Step by Step

Consider this array:

```js
const arr = [1, [2, [3, 4]], 5];
```

Goal:

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

### Step 1

### Read first element:

```js
1
```

It is not an array.

Add directly:

```js
result = [1]
```

* * *

### Step 2

Next element:

```js
[2, [3, 4]]
```

This is an array.

We must go inside it.

* * *

### Step 3

Inside that array:

```js
2
```

Add it:

```js
result = [1, 2]
```

* * *

### Step 4

Next element:

```js
[3, 4]
```

Again, another array.

Go deeper.

* * *

### Step 5

Add elements:

```js
result = [1, 2, 3, 4]
```

* * *

### Step 6

Return to original array.

Last element:

```js
5
```

Final result:

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

This recursive thinking is the key idea behind flattening arrays.

![](https://cdn.hashnode.com/uploads/covers/695a275cee3d7756437f49db/a96f98e3-e344-48cc-aa2d-54ba0dbae3a1.png align="center")

## Different Approaches to Flatten Arrays

### 1\. Using `flat()`

JavaScript provides a built-in method called `flat()`.

Example:

```js
const arr = [1, [2, 3], [4, 5]];

const result = arr.flat();

console.log(result);
```

Output:

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

* * *

### Flattening Deeper Levels

```js
const arr = [1, [2, [3, [4]]]];

console.log(arr.flat(2));
```

Output:

```js
[1, 2, 3, [4]]
```

Depth `2` means flatten two levels.

* * *

### Completely Flattening

```js
console.log(arr.flat(Infinity));
```

Output:

```js
[1, 2, 3, 4]
```

* * *

### Advantages

*   Simple
    
*   Readable
    
*   Fast to write
    

### Disadvantages

*   Not supported in very old browsers
    
*   Interviewers may ask for manual implementation
    

* * *

## 2\. Using Recursion

This is the most important interview approach.

```js
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;
}

const arr = [1, [2, [3, 4]], 5];

console.log(flattenArray(arr));
```

Output:

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

* * *

## Understanding the Logic

### Check Each Element

```js
if (Array.isArray(item))
```

We check whether the current item is an array.

* * *

### If It Is an Array

```js
flattenArray(item)
```

Call the same function again.

This is recursion.

* * *

### If It Is Not an Array

```js
result.push(item)
```

Store directly in result.

* * *

## Visual Recursive Flow

```text
flatten([1, [2, [3]]])

→ 1 added

→ flatten([2, [3]])

    → 2 added

    → flatten([3])

        → 3 added

Final:
[1, 2, 3]
```

* * *

## 3\. Using `reduce()`

This approach is elegant and functional.

```js
function flattenArray(arr) {
  return arr.reduce((acc, item) => {
    if (Array.isArray(item)) {
      return acc.concat(flattenArray(item));
    }

    return acc.concat(item);
  }, []);
}
```

Output:

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

* * *

### Why Developers Like `reduce()`

*   Cleaner functional style
    
*   Compact code
    
*   Common in modern JavaScript
    

But beginners may find recursion with loops easier to understand.

* * *

## 4\. Using Loops Only

This approach avoids recursion.

```js
function flattenArray(arr) {
  const stack = [...arr];
  const result = [];

  while (stack.length) {
    const item = stack.pop();

    if (Array.isArray(item)) {
      stack.push(...item);
    } else {
      result.unshift(item);
    }
  }

  return result;
}
```

* * *

### Why This Approach Matters

Some interviewers ask:

> "Can you solve this without recursion?"

This solution uses a stack-based approach.

It is useful for:

*   Large nested arrays
    
*   Avoiding recursion limits
    

* * *

## Common Interview Scenarios

### Scenario 1: Flatten Only One Level

Input:

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

Expected:

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

* * *

### Scenario 2: Flatten Completely

Input:

```js
[1, [2, [3, [4]]]]
```

Expected:

```js
[1, 2, 3, 4]
```

* * *

### Scenario 3: Flatten to Specific Depth

Input:

```js
[1, [2, [3, [4]]]]
```

Depth:

```js
2
```

Expected:

```js
[1, 2, 3, [4]]
```

* * *

### Scenario 4: Do Not Use `flat()`

Very common interview restriction.

Interviewers want to test:

*   Logical thinking
    
*   Recursion
    
*   Problem decomposition
    

* * *

## Problem Solving Mindset

When solving flattening problems, think in this order:

### 1\. Is the current item an array?

If yes:

```js
Go deeper
```

If no:

```js
Store it
```

* * *

### 2\. Repeat the Process

This repeating behavior naturally suggests recursion.

* * *

### 3\. Build Final Result Gradually

### Do not try to solve everything at once.

Focus on one element at a time.

This mindset helps in many advanced problems too.

* * *

## Time Complexity

### Most flattening approaches take:

```text
O(n)
```

Where `n` is the total number of elements.

Because every element is visited once.

* * *

## Final Thoughts

Array flattening is more than just a JavaScript trick. It teaches an important programming mindset:

*   Breaking problems into smaller parts
    
*   Handling nested structures
    
*   Thinking recursively
    
*   Building reusable logic
    

In real projects, `flat()` is often enough. But for interviews and deeper understanding, recursion and stack-based approaches are extremely valuable.
