Skip to main content

Command Palette

Search for a command to run...

Nested Arrays & Flattening (The Interview Trap Explained 😏)

Published
5 min read
Nested Arrays & Flattening (The Interview Trap Explained 😏)

Alright… today we are going to talk about something which looks simple… but interviews mein logon ki hawa nikal deta hai 😏

Nested Arrays & Flattening

And trust me… if you understand this properly, you will start thinking like a developer… not like a “copy-paste engineer” 😌

Also… I am not going to start with heavy definitions… because honestly… kisi ko samajh nahi aata usse.


So what are Nested Arrays?

Technically…

A nested array is an array inside another array.

Simple? Too simple… suspiciously simple 🤨

Let’s understand it in our way.


Real Life Example

Imagine your WhatsApp groups:

  • Family Group → messages

  • Friends Group → messages

  • Office Group → messages

Now if you store all groups:

[
  ["Hi beta", "Khana khaya?"],
  ["Bhai party kab?", "Match dekha?"],
  ["Deadline kal hai", "Meeting at 10"]
]

This… is a nested array


Visual Structure (Important)

Think like this:

[
  [1, 2],
  [3, 4],
  [5, 6]
]
  • Outer array → main container

  • Inner arrays → sub containers

Or in human language:

“Array ke andar aur array ghus gaya hai”


Problem Starts Here 😏

Now suppose interviewer asks:

👉 “Give me all elements in one single array”

Output should be:

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

Now your brain:

“Easy hai bhai… dekh lenge”

But code likhne baithoge…

Tab samajh aayega asli struggle 😌


What is Flattening?

Flattening means:

👉 Converting nested arrays into a single-level array


Step by Step Thinking (Very Important)

Let’s take:

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

Now think like a developer… not like a student.

Step 1: Check each element

  • 1 → normal number → add

  • [2,3] → array → open it

  • [4,[5,6]] → array → open again


Step 2: Keep opening until no array left

Final result:

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

Why Flattening is Useful?

Let’s be practical…

1. API Data

Sometimes backend sends:

[["apple", "banana"], ["mango"]]

But frontend needs:

["apple", "banana", "mango"]

2. E-commerce Example

Orders:

[
  ["shirt", "pant"],
  ["shoes"],
  ["watch", "belt"]
]

You want:

👉 total items sold

Flatten first → then count


3. Interview Favorite 😏

“Flatten this array without using built-in methods”

And then…

Candidate: 😵‍💫


Different Ways to Flatten Arrays

Now real game starts 🔥


1. Using flat() (Easy Mode 😌)

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

const result = arr.flat();

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

Deep Nested?

arr.flat(Infinity)

2. Using Loop (Manual Thinking 🧠)

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

for (let i = 0; i < arr.length; i++) {
  if (Array.isArray(arr[i])) {
    result.push(...arr[i]);
  } else {
    result.push(arr[i]);
  }
}

console.log(result);

3. Recursive Approach (Interview King 👑)

Now THIS is what interviewer wants.

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

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

  return result;
}

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

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

Why recursion?

Because…

“Array ke andar array ke andar array…”

Kitna andar jayega? 👉 Unknown

So we use recursion.


4. Using reduce()

Little advanced… but sexy 😏

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

const result = arr.reduce((acc, item) => {
  return acc.concat(
    Array.isArray(item) ? flatten(item) : item
  );
}, []);

console.log(result);

Common Interview Scenarios

Now listen carefully… this is gold.


Scenario 1

👉 Flatten array without using .flat()

Expected answer: recursion


Scenario 2

👉 Flatten only one level

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

Output:

[1,2,3,4]

Scenario 3

👉 Flatten to specific depth

arr.flat(2)

Scenario 4

👉 Count total elements in nested array

Hint:

👉 Flatten → then .length


How to Think (Most Important Part)

Whenever you see nested array:

Don’t panic ❌ Don’t jump to code ❌

Ask:

  1. Is this element array?

  2. If yes → go inside

  3. If no → collect it

बस… problem solved.


Diagram Idea (Mental Visualization)

Think like onion layers 🧅

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

You keep peeling layers until:

👉 only numbers left


Small Assignment (Don’t Run 😏)

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

Tasks:

  1. Flatten this array

  2. Count total elements

  3. Find sum of all elements


Final Words

Nested arrays are not difficult…

But your thinking makes it difficult.

Once you understand:

👉 “Check → Dive → Collect”

You can solve ANY flatten problem.


And remember…

Interview mein agar ye question aaya…

Aur aapne recursion laga diya…

Interviewer bolega:

“Yeh banda copy paste nahi karta… sochta hai” 😌🔥


अब जाओ… practice करो… warna next interview mein phir bolna padega:

“Sir… thoda hint de dijiye…” 😭


More from this blog

B

Barun Tiwary

25 posts

Nested Arrays & Flattening (The Interview Trap Explained 😏)