Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

In this article i cover beginner friendly "Array Flatten in JavaScript", step by step, with a story-telling tone, visual imagination, and problem-solving mindset. No heavy jargon. No boredom. Just clarity.

Updated
•5 min read•View as Markdown
Array Flatten in JavaScript

Imagine you opened a school bag, and inside it there are smaller bags, and inside those bags… even more bags

Your task is simple:

👉 Take everything out and put it in one single bag.

That’s is nothing but array flattening in JavaScript.

Let’s understand this slowly and clearly.


What Are Nested Arrays?

First, let’s understand nested arrays.

Simple Array

let numbers = [1, 2, 3, 4];

This is simple. One box. All items inside it.

Nested Array (Array inside Array)

let numbers = [1, [2, 3], [4, [5, 6]]];

Now imagine this visually 👇

[ 1, [ 2, 3 ], [ 4, [ 5, 6 ] ] ]
│
├── 1
├── [2, 3]
│    ├── 2
│    └── 3
└── [4, [5, 6]]
     ├── 4
     └── [5, 6]
          ├── 5
          └── 6

📦 Box inside box inside box — that’s a nested array.


Why Flattening Arrays Is Useful?

Now the another question is raised up by your little brother:

bhayya “Why can’t we just leave it like this?”

Good question, let's understand by taking real life scenario🙂

Real-Life Problems

Most JavaScript functions, loops, and calculations expect one simple array, like this:

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

Problems Without Flattening

❌ Hard to loop
❌ Hard to calculate sum
❌ Hard to search values
❌ APIs and databases usually want flat data

Example

let data = [1, [2, 3], 4];

// ❌ Confusing
data.forEach(item => console.log(item));

Output:

1
[2, 3]
4

But what if you want every number separately?

👉 Here Flattening comes to the picture and shine.


What Is the Concept of Flattening Arrays?

Flattening means:

Removing all inner arrays and putting every value into one single array

Before Flatten

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

After Flatten

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

Flatten Transformation Visual

Before Flatten:
[ 1, [ 2, 3 ], [ 4, [ 5, 6 ] ] ] // box inside box

⬇️  Flattening Process

After Flatten:
[ 1, 2, 3, 4, 5, 6 ] // all boxes in one big box

Think like this:

  • Open every box

  • then, Take items out

  • finally, Put them into one big box


Different Approaches to Flatten Arrays

Now comes the problem-solving part 🧠, as we know every problem has multiple solution, here in flatten arrays we also have multiple approaches

Let’s explore multiple ways, from easiest to interview-level.


Approach 1: Using flat()

JavaScript already gives us a helper method.

let arr = [1, [2, 3], [4, [5, 6]]];
let result = arr.flat(Infinity);

console.log(result);
// [1, 2, 3, 4, 5, 6]

Now let me explain in simplest way whats going on here.

flat() opens inner boxes

Infinity means: “Open all boxes no matter how deep the nesting it is”

Flat method is best for Clean code, Real projects and it makes our work easy.

But in many interview they don't allow to use method:

“Don’t use flat() — do it yourself”

So let’s move on 👇


Approach 2: Using Recursion

This is the heart of array flattening ❤️

Step-by-Step Thinking

  1. Create an empty result array

  2. Loop through items

  3. If item is an array → flatten it again

  4. If item is not an array → push it

Code

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

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

  return result;
}

let data = [1, [2, 3], [4, [5, 6]]];
console.log(flattenArray(data));

Output

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

Simple Explanation

  • If it’s a number → keep it

  • If it’s an array → open it again

  • Keep repeating until no arrays left

🧠 This is what interviewers LOVE.


Recursive Flow

flatten([1, [2, 3]])
│
├── 1 → push
└── [2, 3] → flatten again
     ├── 2 → push
     └── 3 → push

Approach 3: Using reduce() (Functional Style)

This looks scary, but it’s powerful.

function flattenArray(arr) { //[1, [2, 3], [4, [5, 6]]];
  return arr.reduce((acc, item) => {
    if (Array.isArray(item)) {
      acc.push(...flattenArray(item));
    } else {
      acc.push(item);
    }
    return acc;
  }, []);
}

This function goes through each item, flattens any nested arrays using recursion, and collects everything into one flat array.


Common Interview Scenarios

Here’s where many people get stuck 😬

Let’s fix that.

Interview Question 1

Flatten an array without using flat(), do not hesitate at that time think throughly.

Use recursion | Explain your thinking | Don’t jump straight to code


Interview Question 2

Flatten only one level

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

arr.flat(1);
// [1, 2, 3, 4]

Explain:

  • Depth = 1 → open only first level

Interview Question 3

Time Complexity

  • Each element visited once

  • Time Complexity: O(n)

  • Space Complexity: O(n)


Conclusion

📦 Nested array = box inside box

📦 Flattening = opening all boxes

📦 Goal = one clean list

When to Use What?

Situation Best Choice
Real project flat()
Interview Recursion
Functional style reduce()