Skip to main content

Command Palette

Search for a command to run...

Flatten the Mess: Master Nested Arrays with Visuals

Updated
•4 min read•View as Markdown

📦 Understanding Nested Arrays & How to Flatten Them (With Visuals)

When you start working with real-world data in JavaScript, arrays rarely stay simple. They become nested, messy, and harder to process.

This article breaks down what nested arrays are, why flattening matters, and how to solve it like an interviewer expects—with visuals and step-by-step thinking.


🔹 What Are Nested Arrays?

A nested array is simply an array inside another array.

Example:

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

Visual Representation:

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

Think of it like a tree:

         []
       /  |   \
      1  []   []
        /  \   |
       2    3  4
                \
                []
               /  \
              5    6

🔹 Why Flattening Arrays Is Useful

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

Example:

Input:  [1, [2, 3], [4, [5, 6]]]
Output: [1, 2, 3, 4, 5, 6]

Real-world use cases:

  • API responses (deeply nested JSON)

  • Form data processing

  • Data normalization

  • Preparing data for loops, maps, filters

👉 Most array operations (map, filter) expect flat arrays


🔹 Concept of Flattening (Core Idea)

Flattening is about:

“Traverse every element. If it's an array → go deeper. If it's a value → collect it.”

Step-by-step transformation:

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

Step 1: Take 1 → add → [1]

Step 2: See [2,3] → open it
        → add 2, 3 → [1,2,3]

Step 3: See [4, [5,6]] → open it
        → add 4
        → see [5,6] → open
        → add 5,6

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

🔹 Different Approaches to Flatten Arrays


✅ 1. Built-in Method (flat())

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

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

✔ Simple

✔ Readable

✔ Handles deep nesting


✅ 2. Recursive Approach (Most Important)

This is the interview favorite.

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

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

  return result;
}

🧠 Thinking Pattern:

  • "If array → recurse"

  • "If value → store"


✅ 3. Using reduce()

function flatten(arr) {
  return arr.reduce((acc, item) => {
    if (Array.isArray(item)) {
      return acc.concat(flatten(item));
    }
    return acc.concat(item);
  }, []);
}

✔ Functional style

✔ Compact


✅ 4. Iterative (Stack-Based)

function flatten(arr) {
  const stack = [...arr];
  const result = [];

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

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

  return result.reverse();
}

✔ No recursion

✔ Good for large inputs (avoids call stack limits)


🔹 Flatten Transformation Diagram

Nested Input:
[1, [2, 3], [4, [5, 6]]]

        ↓ open arrays

Step-wise Expansion:
[1, 2, 3, 4, [5, 6]]

        ↓ open again

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

🔹 Common Interview Scenarios

🧩 1. Flatten up to depth k

arr.flat(2); // flatten only 2 levels

🧩 2. Custom flatten function without flat()

👉 Use recursion (expected answer)


🧩 3. Flatten and remove duplicates

[...new Set(flatten(arr))]

🧩 4. Flatten + transform

flatten(arr).map(x => x * 2);

🧩 5. Deep nested JSON traversal

Same concept applies beyond arrays:

  • Trees

  • Objects

  • DOM


🔹 Key Takeaways

  • Nested arrays = hierarchical structure

  • Flattening = converting to linear structure

  • Core idea = recursive traversal

  • Most important skill = recognizing when to go deeper


🚀 Final Thought

Flattening isn’t just an array trick—it’s a pattern:

“When data is nested → traverse recursively → extract values”

Master this once, and it applies to:

  • Trees

  • Graphs

  • File systems

  • JSON APIs

3 views