Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Published
6 min read
Array Flatten in JavaScript
S
I write code , that run in the browser and someone else's machine. And sometimes I also write articles

When working with real-world data, arrays are not always simple lists of values. Very often, they contain other arrays inside them. This structure is called a nested array.

Understanding how to flatten nested arrays is not just about memorizing a method. It is about learning how to think step by step when handling structured data.

Let us build this concept carefully and practically.


What Are Nested Arrays

A nested array is simply an array that contains other arrays as elements.

Basic Example

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

Visually, this looks like:

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

The third element is itself an array.

Here is a more complex example:

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

Visually:

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

Here we have multiple levels of nesting. Some elements are numbers, some are arrays, and some arrays contain more arrays.

This is where flattening becomes important.


What Does Flattening Mean

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

For example:

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

Becomes:

[1, 2, 3, 4, 5]

And:

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

Becomes:

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

The goal is simple: remove nesting while keeping all values.


Why Flattening Is Useful

Flattening is common in real-world applications.

Imagine:

  • An API returns nested category data

  • A form returns grouped values

  • A tree structure needs to become a simple list

  • You want to run map() or filter() on all values

Most array methods work best on one-dimensional arrays. Flattening helps simplify complex data structures.

It is also a very common coding interview question because it tests logical thinking and recursion skills.


Thinking Through the Problem

Before writing any code, think carefully.

Take this example:

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

Ask yourself:

  • What do I want as output

  • How do I know if something is an array

  • What should I do if it is an array

  • What should I do if it is not

The thinking pattern should be:

If the current item is not an array, keep it.
If the current item is an array, open it and process it again.

This idea of repeating the same process is the foundation of recursion.


Approach 1: Using the Built-in flat() Method

Modern JavaScript provides a built-in solution.

One Level Flattening

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

const result = numbers.flat();

console.log(result);

Output:

[1, 2, 3, 4, 5]

By default, flat() removes only one level of nesting.


Flattening Multiple Levels

If the nesting is deeper:

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

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

The number 2 means flatten up to two levels.

If you do not know how deep the nesting is:

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

Using Infinity tells JavaScript to flatten completely.

This is the easiest solution, but in interviews you are often asked to solve it without using flat().


Approach 2: Recursive Solution

Now let us think manually.

Suppose we want to flatten this:

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

We go through each element one by one.

  • 1 → not an array → add to result

  • [2, [3, 4], 5] → this is an array → process it again

  • 6 → not an array → add to result

That repeated processing is recursion.

Implementation

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

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

  return result;
}

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

Step by Step What Happens

  1. The function receives the main array.

  2. It loops through each element.

  3. If the element is an array, it calls itself again.

  4. If it is a number, it pushes it into the result.

  5. It keeps repeating until no nested arrays remain.

The key thinking is not about syntax. It is about identifying when to repeat the same logic.


Approach 3: Using reduce()

Another common interview approach uses reduce().

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

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

Here is the reasoning:

  • Start with an empty array

  • For every element:

    • If it is an array, flatten it and merge

    • If it is a value, just merge it

This solution works for unlimited nesting depth.


Flattening Only One Level Manually

If the array is nested only one level, the logic can be simpler.

const numbers = [1, 2, [3, 4], 5];
const result = [];

for (let item of numbers) {
  if (Array.isArray(item)) {
    for (let value of item) {
      result.push(value);
    }
  } else {
    result.push(item);
  }
}

console.log(result);

This works only for one level because it does not handle nested arrays inside nested arrays.

The important lesson is recognizing limitations of your solution.


More Practice Example

Flatten this array:

const mixed = [1, ["a", ["b", "c"]], 2, [3]];

Expected output:

[1, "a", "b", "c", 2, 3]

When you look at this, your brain should automatically think:

  • Check each item

  • If it is an array, open it

  • Repeat the process

That structured thinking is more important than memorizing code.


Common Interview Variations

Interviewers may modify the problem slightly:

Flatten up to a specific depth:

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

Expected output:

[1, 2, [3]]

Or:

Flatten and remove duplicates:

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

Expected output:

[1, 2, 3]

These variations test whether you understand the structure deeply rather than relying on a built-in method.


Key Ideas to Remember

When facing nested array problems:

  • Always define the expected output clearly

  • Identify whether each element is an array

  • Decide what to do for arrays and non-arrays

  • Think in terms of repeating logic

The core rule is simple:

If it is an array, process it again.
If it is not, store it.

That mental model makes flattening natural rather than complicated.


Final Understanding

Nested arrays contain arrays within arrays. Flattening transforms them into a single-level structure.

You can flatten arrays using:

  • The built-in flat() method

  • Recursion with loops

  • Recursion with reduce()

More importantly, flattening teaches structured thinking about nested data. Once you understand the logic behind it, you can apply the same approach to trees, JSON structures, and many other real-world problems in JavaScript.