Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
4 min read
Array Flatten in JavaScript

Hello readers,

Welcome to another blog in this JS series. In the previous blogs, I've covered concepts like destructuring, spread/rest, and template literals. Now it’s time to tackle something that looks simple but is asked very frequently in interviewsArray Flattening in JavaScript.

Array flattening is a simple but very useful concept. There are various ways to flatten a nested array. In this blog, I will cover all those from the perspective of an interview.

Let's start the blog.

Nested Arrays

A nested array is simply an array inside another array.

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

But this can be deeper like this:

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

You can think of it as the layer of boxes inside boxes.

Why flatten nested arrays?

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

//nested array
[1, [2, [3, 4]], 5]

// flatten array - single level
[1, 2, 3, 4, 5]

Real-world use cases:

  • API responses (nested JSON data)

  • Data transformation before rendering UI

  • Processing deeply nested structures (like comments, categories)

  • Interview problems (VERY common)

Ways to flatten arrays

We can flatten an array in 3 steps only, and those are:

  1. Traverse every element of the nested array

  2. If the element is an array, then go deeper.

  3. Now, when you find a value, then collect that.

Example:

//nested array
[1, [2, [3, 4]], 5]

steps to make this single level array
Step 1: 1 → add → [1]

Step 2: [2, [3, 4]] → go inside
        2 → add → [1, 2]

        [3, 4] → go inside
        3 → add → [1, 2, 3]
        4 → add → [1, 2, 3, 4]

Step 3: 5 → add → [1, 2, 3, 4, 5]

Here are the different ways to flatten a nested array.

1. Using flat()

This is a built-in method in JS used to flatten the array.

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

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

This method takes depth as an argument. Default depth is 1, and if you have flattened the array fully, then you can use Infinity

💡
flat() method also removes the empty slots automatically

2. Using Recursion

In the interview, the interviewers expect you to use raw code, not an built-it method.

Here is the recursive way to flatten an array.

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

In this code:

  • I have iterated through array

  • Check → is it an array?

  • Yes → recursively flatten

  • No → push to result

3. Using reduce()

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

This is the same as the above recursion idea, but cleaner code.

4. Using Stack

Recursion is not useful for large arrays. So, you can also use a stack if the array length is large.

function flattenArray(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();
}

At the end, reversed because the stack is LIFO (last in first out)

5. Using toString()

This can also flatten a nested array but is not recommended because it converts everything to a string and will also break for objects or booleans inside the array.

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

const result = arr.toString().split(',').map(Number);

That’s it for this blog. This is one of those concepts that looks easy at first, but once you go deeper, you’ll realize how important it is for interviews and real-world problem-solving. Make sure you don’t just read it—try implementing each approach yourself.

In the next blog, we’ll dive into another interesting JavaScript concept that will level up your understanding even more.

Till then...

Stay consistent and keep grinding....

Peace ✌️

Array Flatten in JavaScript