Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
2 min read

What are Nested Arrays?

A nested array is simply an array inside another array.

Example:

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

Think of it like folders inside folders .

Why Flattening Arrays is Useful?

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

Why this matters:

  • Easier to loop through data

  • Required for APIs / data processing

  • Useful in frontend rendering (React lists, etc.)

  • Simplifies calculations (sum, filter, map)

Example:

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

Concept of Flattening (Step-by-Step Thinking)

Take this:

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

Step-by-step:

  1. Start with empty result → []

  2. Read 1 → push → [1]

  3. See [2, [3, 4]] → go inside

  4. Read 2[1, 2]

  5. See [3, 4] → go inside

  6. Push 3, 4[1, 2, 3, 4]

Key idea:
If element is an array → go deeper (recursion)
If not → add to result

Different Approaches to Flatten Arrays

1. Built-in Method (flat())

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

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

2. Using Recursion(most important)

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;
}

3. Using Stack (Iterative Approach)

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

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

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

  return result.reverse();
}

4. Using reduce()

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

Common Interview Scenarios

  1. Flatten to a specific depth
arr.flat(2)
  1. Flatten without using built-in methods

  2. Handle very deeply nested arrays
    recursion vs stack discussion

  3. Flatten + remove duplicates

[1, [2, 2], [3]] → [1, 2, 3]
  1. Flatten + transform
[1, [2, 3]] → [2, 4, 6] (map while flattening)

Problem-Solving Thinking (What Interviewers Want)

When you see a nested array:

Ask yourself:

  1. Is this recursive in nature? → YES

  2. What is the base case? → Not an array

  3. What should I do with sub-arrays? → Flatten them

1 views