Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
•9 min read•View as Markdown
A
I write tech education content

Imagine you and your friend are sitting in a café, coffee in hand, and your friend suddenly says:

“Hey, I have an array inside another array… and then another one inside that. How do I make this look simple?”

That is exactly where array flattening comes in.

In JavaScript, flattening an array means taking a nested array and turning it into a single-level array. It is one of those concepts that looks small at first, but once you understand it properly, it starts showing up everywhere — in coding interviews, data processing, UI logic, and even real-world app development.

Let us break it down in a simple way.


What nested arrays are

A nested array is just an array that contains another array inside it.

For example:

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

Here, the array is not flat. It has different levels inside it.

Think of it like a set of boxes:

  • one big box

  • inside it, some smaller boxes

  • inside those smaller boxes, maybe even more boxes

So instead of having a clean list like:

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

you get:

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

That is a nested structure.


Why flattening arrays is useful

Now you may ask, “Why do we even need flattening?”

Good question.

Flattening becomes useful when data comes in a nested form, but your logic needs a simple one-dimensional list.

Here are a few common cases:

  • when working with API responses

  • when merging grouped data

  • when processing lists from loops or maps

  • when preparing data for search, filter, or display

  • when solving coding interview problems

For example, suppose you get this data:

const students = [
  ["Aman", "Ravi"],
  ["Sita", "Neha"],
  ["John", "Priya"]
];

If you want to treat all names as one list, flattening helps:

["Aman", "Ravi", "Sita", "Neha", "John", "Priya"]

That is much easier to work with.


Concept of flattening arrays

Flattening simply means removing the extra nesting.

Let us look at this example:

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

A single-level flatten would look like:

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

A full flatten would look like:

[1, 2, 3, 4, 5]

So the main idea is:

  • find array values

  • go inside nested arrays

  • bring all values to one level

That is the whole concept in simple words.


Different approaches to flatten arrays

There are several ways to flatten arrays in JavaScript. Some are built-in, and some are custom solutions.

Let us go through them one by one.


1. Using flat() method

The easiest way in modern JavaScript is the built-in flat() method.

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

console.log(arr.flat());

Output:

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

By default, flat() flattens only one level.

If you want deeper flattening, pass the depth:

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

Output:

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

If you want to flatten all levels, you can also use:

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

Why it is useful

  • simple

  • readable

  • clean

  • perfect for modern JavaScript

Limitation

It may not be available in very old environments.


2. Using recursion

Recursion is one of the most common custom ways to flatten arrays.

Here is a simple version:

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

const arr = [1, [2, 3], [4, [5, 6]]];
console.log(flattenArray(arr));

Output:

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

How it works

Let us understand it step by step.

For this array:

[1, [2, 3], [4, [5, 6]]]
  • 1 is a normal value, so it gets added directly

  • [2, 3] is an array, so the function calls itself again

  • [4, [5, 6]] is also an array, so recursion continues

  • finally, everything is collected into one flat list

This method is beautiful because it matches the real logic of nested structures.


3. Using reduce()

Another elegant way is to use reduce().

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

const arr = [1, [2, 3], [4, [5, 6]]];
console.log(flattenArray(arr));

Output:

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

Why this works well

reduce() helps build a new array step by step.

  • start with an empty array

  • check each item

  • if item is an array, flatten it

  • if item is a normal value, add it

This approach is very common in interview answers because it shows good understanding of array methods.


4. Using loop and stack

This is a more problem-solving style approach.

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

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

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

  return result;
}

const arr = [1, [2, 3], [4, [5, 6]]];
console.log(flattenArray(arr));

Output:

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

What is happening here

  • we use a stack to keep track of items

  • if an item is an array, we push its values back

  • if it is a normal value, we put it in the result

  • using unshift() helps maintain the correct order

This approach may feel a little tricky at first, but it is a good one to understand for interviews.


Step by step flattening example

Let us take this array:

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

Step 1

Take 1 → add to result

[1]

Step 2

Take [2, [3, 4]] → go inside it

Now we get:

[2, [3, 4]]

Step 3

Take 2 → add to result

[1, 2]

Step 4

Take [3, 4] → go inside again

Now we get:

[3, 4]

Step 5

Add 3 and 4

[1, 2, 3, 4]

Step 6

Take 5 → add to result

Final output:

[1, 2, 3, 4, 5]

That is flattening in action.


Visual nested array example

Here is a simple way to imagine it:

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

Think of it like this:

1
2 3
4
5 6

After flattening, everything becomes one clean line:

1, 2, 3, 4, 5, 6

This mental picture helps a lot when solving array problems.


Common interview scenarios

Flattening arrays is a very popular interview topic because it checks more than just syntax.

It checks whether you understand:

  • recursion

  • array methods

  • problem decomposition

  • data structure thinking

Here are some common interview-style questions:

1. Flatten an array up to one level

Example:

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

Expected:

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

2. Flatten an array completely

Example:

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

Expected:

[1, 2, 3, 4]

3. Flatten without using built-in flat()

This is a favorite interview twist.

4. Write a recursive flatten function

This tests whether you can break a nested problem into smaller parts.

5. Flatten and remove duplicates

Sometimes interviewers combine flattening with other logic.

Example:

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

Expected unique result:

[1, 2, 3, 4]

Which method should you use?

That depends on the situation.

Use flat() when:

  • you want the simplest solution

  • you are working in modern JavaScript

  • readability matters most

Use recursion when:

  • you want to understand the logic deeply

  • you are solving interview problems

  • you need to flatten deeply nested arrays

Use reduce() when:

  • you want a functional style

  • you want a neat custom solution

Use stack-based method when:

  • you want to show strong problem-solving skills

  • you are handling nested structures in a more manual way


A simple custom flatten function

Here is a clean recursive version you can remember for interviews:

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

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

  return result;
}

console.log(flattenArray([1, [2, 3], [4, [5, 6]]]));

This one is easy to explain in an interview:

  • loop through array

  • check if element is an array

  • if yes, flatten it recursively

  • if no, push it to result

Simple and solid.


Final thoughts

Array flattening is one of those JavaScript topics that feels basic at first, but teaches a lot of important things behind the scenes.

It helps you understand:

  • nested data

  • recursion

  • array processing

  • clean problem solving

And honestly, once you understand flattening, many other nested structure problems start feeling much easier.

So the next time you see something like:

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

do not panic.

Just smile, take a sip of coffee, and flatten it step by step.


Conclusion

Array flattening in JavaScript means converting nested arrays into a single-level array. You can do it with flat(), recursion, reduce(), or even a stack-based approach. It is useful in real-world coding and very common in interviews.

If you understand the logic behind it, not just the syntax, you will be in a much stronger position while solving array problems in JavaScript.

JavaScript Gyan404

Part 24 of 24

In this series of JavaScript Gyan404 I am going to write about almost everything I know about JavaScript.

Start from the beginning

JavaScript Operators

The Basics You Need to Know