# Flattening Nested Arrays in JavaScript 

Imagine you ordered a pizza that came inside a box, inside another box, inside a bag. You just want the pizza — not all those layers of packaging. Nested arrays in JavaScript work exactly like that. You have data wrapped in layers of arrays, and sometimes you just need everything in one flat list.

Flattening is the process of removing those layers. It's a concept that comes up constantly in real projects and is a favourite in technical interviews. Let's break it down step by step.

**What are Nested Arrays?**

A nested array is simply an array that contains other arrays as its elements — instead of just plain values.

```js
// A regular flat array
const flat = [1, 2, 3, 4, 5];

// A nested array — arrays inside an array
const nested = [1, [2, 3], [4, [5, 6]]];

// Deeply nested — many levels deep
const deep = [1, [2, [3, [4, [5]]]]];
```

Each `[...]` inside the outer array is a level of nesting. The value `5` in the deeply nested example is buried four levels down.

This happens in real code all the time — when you fetch data from multiple API calls, when you build menus with sub-menus, or when you group items into categories.

```javascript
// Real-world example: grouped tags from a blog
const tagGroups = [
  ["javascript", "es6"],
  ["react", "hooks"],
  ["css", "flexbox", "grid"]
];

// You want: ["javascript", "es6", "react", "hooks", "css", "flexbox", "grid"]
```

**Why is Flattening Useful?**

Nested arrays are great for organising data into groups — but they become a problem the moment you want to work with all the values together.

Say you want to count all tags, remove duplicates, or search for a specific item. If the data is nested, you'd have to loop through multiple layers. Flattening gives you a single clean array to work with.

```javascript
const tagGroups = [["javascript", "es6"], ["react", "hooks"]];

// Hard: searching in nested arrays
// You'd need a nested loop

// Easy: search in a flat array
const allTags = tagGroups.flat();
console.log(allTags.includes("react")); // true
```

Flattening is essentially data cleanup — taking structure designed for organisation and converting it into a shape designed for processing.

**The Concept of Flattening — Step by Step**

Think of flattening as going through an array and, whenever you find another array inside it, pulling its contents out and placing them directly in the parent.

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

Step 1: Look at element 1 → it's a plain number → keep it → [1]
Step 2: Look at [2, 3] → it's an array → pull it out → [1, 2, 3]
Step 3: Look at [4, 5] → it's an array → pull it out → [1, 2, 3, 4, 5]

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

One level of nesting removed. If there were arrays *inside* those inner arrays, you'd need to go deeper — which is where the concept of "depth" comes in.

```javascript
Level 1 flat: [1, [2, [3]]]  →  [1, 2, [3]]   (inner [3] still wrapped)
Level 2 flat: [1, [2, [3]]]  →  [1, 2, 3]     (fully flat)
```

**Different Approaches to Flatten Arrays**

**Approach 1 —** `Array.flat()` **(modern, simplest)**

JavaScript has a built-in method for this. `flat()` by default removes one level of nesting. Pass a depth number to go deeper. Pass `Infinity` to flatten no matter how deep.

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

console.log(arr.flat());       // [1, 2, 3, 4, [5, 6]] — one level
console.log(arr.flat(2));      // [1, 2, 3, 4, 5, 6]   — two levels
console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5, 6] — all levels
```

```javascript
// Real-world: flatten grouped tags
const tagGroups = [["javascript", "es6"], ["react", "hooks"], ["css"]];
const allTags = tagGroups.flat();

console.log(allTags); // ["javascript", "es6", "react", "hooks", "css"]
```

Use `flat()` whenever you can — it's clean and readable.

**Approach 2 —** `flatMap()` **(flatten + transform in one step)**

`flatMap()` maps over each element and then flattens the result by one level. It's like doing `.map()` followed by `.flat(1)` — but in a single call.

```js
const sentences = ["Hello world", "JS is fun"];

// Split each sentence into words, then flatten into one word list
const words = sentences.flatMap(s => s.split(" "));

console.log(words); // ["Hello", "world", "JS", "is", "fun"]
```

```js
// Another example: duplicate each number
const nums = [1, 2, 3];
const doubled = nums.flatMap(n => [n, n]);

console.log(doubled); // [1, 1, 2, 2, 3, 3]
```

`flatMap()` is ideal when you're transforming *and* flattening at the same time.

**Common Interview Scenarios**

**Scenario 1 — "Flatten this array without using** `.flat()`**"**

```js
// Using reduce — the expected interview answer
function flatten(arr) {
  return arr.reduce((acc, item) =>
    Array.isArray(item) ? acc.concat(flatten(item)) : [...acc, item],
  []);
}

console.log(flatten([1, [2, [3, [4]]]])); // [1, 2, 3, 4]
```

**Scenario 2 — "Get all unique tags from nested groups"**

```js
const tagGroups = [["js", "es6"], ["js", "react"], ["css", "es6"]];

const uniqueTags = [...new Set(tagGroups.flat())];
console.log(uniqueTags); // ["js", "es6", "react", "css"]
```

Notice how this combines `flat()` from this topic with `Set` from the previous blog — concepts stack!

**Scenario 3 — "Count total items across nested lists"**

```js
const inventory = [["apple", "mango"], ["pen", "notebook", "eraser"], ["water"]];

const totalItems = inventory.flat().length;
console.log(totalItems); // 6
```

**Scenario 4 — "Extract all numbers from a mixed nested array"**

```js
const mixed = [1, ["hello", 2], [3, ["world", 4]]];

const numbers = mixed.flat(Infinity).filter(item => typeof item === "number");
console.log(numbers); // [1, 2, 3, 4]
```

**Quick Summary**

*   Nested arrays are arrays that contain other arrays — they can go many levels deep
    
*   Flattening means pulling inner arrays out and merging everything into one flat list
    
*   `flat(depth)` is the modern built-in — use `Infinity` for unknown depths
    
*   `flatMap()` maps and flattens in one step
    
*   `reduce()` and recursion are the interview-expected manual approaches
    
*   The core question to always ask: "how many levels deep does this go?"
    

  
**First — the nested array structure visualised as layers:**

![](https://cdn.hashnode.com/uploads/covers/644510985259d501cf938e64/dbaeb866-1fdb-4fc1-b757-d29352e88db9.png align="center")

**Second — the flattening transformation: before, step by step, and after:**

![](https://cdn.hashnode.com/uploads/covers/644510985259d501cf938e64/0d52ad4a-54df-4f16-bf03-23979940dbd5.png align="center")
