Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

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

Flattening array is one of those concepts that seems simple at first -- but shows up everywhere once we start solving real problems or preparing for interviews.

In this blog, I'll break it down step-by-step, no only how to flatten arrays, but also understand the thinking behind it.

What Are Nested Arrays?

A nested array is simply an array inside another array.

Example:

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

This is called nested array.

Visual Representation:

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

Think of it like boxes inside boxes.

Why Flattening Arrays is Useful

Working with nested arrays is difficult because:

  • Iterating becomes complex

  • Data is harder to process

  • APIs often expect flat structures

Real World use cases:

  • API Responses

  • Tree/graph data

  • UI rendering lists

  • Data transformation pipelines

What Does Flattening Mean?

Flattening means converting:

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

into:

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

Step-by-Step Flattening (Thinking Process)

Let's break it down visually:

Step 1:

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

Take 1 --> it's not an array keep it

Step 2:

[2, 3]

Open it and take elements out

Step 3:

[4, [5, 6]]

Again, open nested arrays

Final Output:

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

Different Approaches To Flatten Array

Using flat() (Modern JavaScript)

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

const result = arr.flat(Infinity);

console.log(result);

Mental Diagram:

flat(Infinity)
   ↓
Removes all nesting levels

Pros:

  • Simple

  • Clean

  • Built-in

Cons:

  • Not supported in very old browser

Using Recursion

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

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

  return result;
}

Visual recursion flow

flatten([1, [2, [3]]])

→ 1 (push)
→ flatten([2, [3]])
     → 2 (push)
     → flatten([3])
          → 3 (push)

Key thinking:

  • “If it's an array → go deeper”

  • “If it's a value → collect it”

Using reduce()

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

Concept:

accumulator + current value
→ keep merging results

Using Stack

This avoid recursion

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

  while (stack.length) {
    let next = stack.pop();

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

  return result.reverse();
}

Visual Flow

Stack → Process → Result

Common Interview Scenarios

1. Flatten to a Specific Depth

arr.flat(1); // only one level

2. Custom Implementation of flat()

Interviewer may ask:

“Implement your own flat function”

3. Handle Large Data

  • Recursion → may cause stack overflow

  • Iterative → better for large inputs

4. Preserve Order

Always ensure

Input order === Output order

Visual Comparison

Method        | Difficulty | Interview Value
-------------|------------|----------------
flat()       | Easy       | Low
Recursion    | Medium     | High 
Reduce       | Medium     | High
Stack        | Hard       | Very High 

Benefits of Flattening

  • Cleaner Data

  • Easier Iteration

  • Better Compatibility with APIs

  • Simplifies logic