# Array Flatten in JavaScript

Arrays are one of the most commonly used data structures in JavaScript. Sometimes, arrays can contain other arrays inside them. These are called **nested arrays**.

Working with nested arrays is very common in real-world applications and coding interviews.

In this article, we’ll learn:

*   What nested arrays are
    
*   Why flattening arrays is useful
    
*   What array flattening means
    
*   Different ways to flatten arrays
    
*   Common interview scenarios
    

Let’s start with the basics.

* * *

### What Are Nested Arrays?

A nested array is simply an array that contains other arrays inside it.

Example:

```javascript
let arr = [1, 2, [3, 4], [5, 6]];
```

Visual representation:

```id="5j3d33"
[
  1,
  2,
  [3, 4],
  [5, 6]
]
```

Here:

*   `1` and `2` are normal elements
    
*   `[3, 4]` and `[5, 6]` are arrays inside the main array
    

* * *

### Why Is Flattening Arrays Useful?

Sometimes we want all elements in a **single array** instead of nested arrays.

Example:

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

Flattened version:

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

Flattening is useful when:

*   Processing API data
    
*   Working with matrix-like structures
    
*   Preparing data for loops
    
*   Solving coding interview problems
    

* * *

### What Does Flattening Mean?

Flattening means converting:

```id="zq52h6"
Nested Array
      ↓
Single-Level Array
```

Example:

```javascript
let arr = [1, [2, [3, 4]]];
```

Flattened result:

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

* * *

### Visual Transformation

```id="x7c2z6"
[1, [2, [3, 4]], 5]

        ↓

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

The nested structure becomes a simple flat array.

* * *

### Approach 1: Using `flat()`

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

Example:

```javascript
let arr = [1, 2, [3, 4]];

let result = arr.flat();

console.log(result);
```

Output:

```id="uw4g8k"
[1, 2, 3, 4]
```

* * *

### Flattening Deeper Arrays

Example:

```javascript
let arr = [1, [2, [3, 4]]];

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

Output:

```id="nd6exl"
[1, 2, 3, 4]
```

The number `2` tells JavaScript how deep to flatten.

* * *

### Using `Infinity`

If we don’t know the depth, we can use `Infinity`.

Example:

```javascript
let arr = [1, [2, [3, [4, 5]]]];

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

Output:

```id="dn71jm"
[1, 2, 3, 4, 5]
```

* * *

### Approach 2: Using a Loop

We can flatten arrays manually using loops.

Example:

```javascript
let arr = [1, 2, [3, 4]];

let result = [];

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

console.log(result);
```

Output:

```id="7hsggq"
[1, 2, 3, 4]
```

This approach helps us understand the flattening process step by step.

* * *

### Step-by-Step Thinking

Example:

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

Process:

```id="50vb77"
Take 1 → add to result

Take [2,3]
  → extract 2
  → extract 3

Take 4 → add to result
```

Final result:

```id="4p1ytm"
[1, 2, 3, 4]
```

This problem-solving approach is important for interviews.

* * *

### Approach 3: Using Recursion

Recursion is commonly used for deeply nested arrays.

Example:

```javascript
function flattenArray(arr) {
  let result = [];

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

  return result;
}

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

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

Output:

```id="m4m5px"
[1, 2, 3, 4, 5]
```

* * *

### How Recursion Works

```id="4d2n6r"
flatten([1,[2,[3]]])

→ take 1
→ flatten([2,[3]])
       → take 2
       → flatten([3])
              → take 3
```

The function keeps going deeper until all nested arrays are processed.

* * *

### Common Interview Scenarios

Array flattening is a very popular interview question.

Interviewers may ask:

*   Flatten an array without using `flat()`
    
*   Flatten only one level
    
*   Flatten deeply nested arrays
    
*   Write a recursive solution
    
*   Optimize the flattening process
    

Example interview input:

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

Expected output:

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

* * *

### `flat()` vs Recursive Approach

| Method | Easy to Write | Handles Deep Nesting | Interview Friendly |
| --- | --- | --- | --- |
| `flat()` | ✅ | ✅ | ❌ |
| Loop | ✅ | ❌ | ✅ |
| Recursion | Moderate | ✅ | ✅ |

* * *

## Practice Assignment

Try these exercises yourself.

* * *

### 1\. Flatten One Level

Input:

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

Expected Output:

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

* * *

### 2\. Flatten Deeply Nested Arrays

Input:

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

Expected Output:

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

* * *

### 3\. Try Without Using `flat()`

Use:

*   loops
    
*   recursion
    
*   `concat()`
    

This will improve your problem-solving skills.

* * *

And now, you know what Array Flatten in JavaScript is.

If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.

Thanks for reading, and see you in the next blog!

Peace ✌️ and Happy Learning!
