Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
7 min readView as Markdown

When working with arrays in JavaScript, you’ll often encounter arrays inside other arrays.

These are called nested arrays.

At first, nested arrays may seem simple. But once data becomes deeply structured, working with it can become difficult.

That’s where array flattening becomes useful.

Flattening converts nested arrays into a single, simpler array structure.

In this blog, you’ll learn:

  • What nested arrays are

  • What flattening means

  • Why flattening is useful

  • Different ways to flatten arrays

  • Common interview scenarios


What Are Nested Arrays?

A nested array is simply:

An array that contains other arrays.


Example of a Nested Array

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

Here:

  • The main array contains smaller arrays inside it

Visual Structure of a Nested Array

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

You can think of it like boxes inside boxes.


More Deeply Nested Example

let data = [1, [2, [3, 4]], 5];

Visual structure:

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

Now the nesting becomes deeper.


Why Flattening Arrays Is Useful

Nested arrays are common in:

  • APIs

  • Database responses

  • Tree structures

  • Menus

  • Category systems

  • Comments/replies

  • Data processing

But many operations become easier when data is flat.

For example:

  • Searching

  • Filtering

  • Mapping

  • Calculating totals

Flattening converts complex structures into simpler arrays.


What Does Flattening Mean?

Flattening means:

Converting nested arrays into a single-level array.


Before Flattening

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

After Flattening

[1, 2, 3, 4, 5]

All nested elements move into one array.


Flatten Transformation Visual

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

        ↓ Flatten

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

Conceptual Thinking Behind Flattening

When flattening arrays:

  • If the item is a normal value → keep it

  • If the item is another array → open it and extract values

This process continues until everything becomes flat.


Approach 1: Using flat()

JavaScript provides a built-in method called flat().

This is the easiest approach.


Basic Example

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

let result = numbers.flat();

console.log(result);

Output

[1, 2, 3, 4, 5]

How flat() Works

[1, [2, 3], [4, 5]]
          ↓
      flat()
          ↓
[1, 2, 3, 4, 5]

Flattening Deeper Arrays

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


Example

let data = [1, [2, [3, 4]]];

console.log(data.flat());

Output

[1, 2, [3, 4]]

Notice:

  • [3, 4] is still nested

Using flat(2)

let data = [1, [2, [3, 4]]];

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

Output

[1, 2, 3, 4]

The number tells JavaScript how deep to flatten.


Using flat(Infinity)

If you don’t know the nesting depth:

let data = [1, [2, [3, [4, 5]]]];

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

Output

[1, 2, 3, 4, 5]

This completely flattens the array.


Approach 2: Using Loops

Before flat() existed, developers used loops.

This approach is useful for understanding the logic.


Example Using forEach()

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

numbers.forEach(function(item) {
  if(Array.isArray(item)) {
    result.push(...item);
  } else {
    result.push(item);
  }
});

console.log(result);

Output

[1, 2, 3, 4, 5]

Understanding the Logic

Step-by-step:

  • Check each item

  • If it’s an array → spread values

  • Otherwise → push normally

This is important interview thinking.


Approach 3: Using Recursion

Recursion is commonly asked in interviews for flattening arrays.

This approach handles deeply nested arrays manually.


Recursive Flatten Function

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

  arr.forEach(function(item) {
    if(Array.isArray(item)) {
      result = result.concat(flattenArray(item));
    } else {
      result.push(item);
    }
  });

  return result;
}

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

Output

[1, 2, 3, 4, 5]

Why Recursion Works

Recursion means:

A function calling itself.

Here:

  • If an item is an array

  • The function flattens it again

This continues until no nested arrays remain.


Recursive Flatten Thinking

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

1 → keep

[2, [3, 4]]
    ↓ flatten again

2 → keep

[3, 4]
    ↓ flatten again

3 → keep
4 → keep

Common Interview Scenarios

Flattening arrays appears frequently in coding interviews.

Especially when testing:

  • Recursion

  • Array manipulation

  • Problem-solving skills


Common Interview Questions

1. Flatten One Level

Input:

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

Output:

[1, 2, 3, 4, 5]

2. Flatten Deeply Nested Arrays

Input:

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

Output:

[1, 2, 3, 4]

3. Flatten Without Using flat()

Very common interview restriction.

Interviewers want to test:

  • Logic

  • Recursion

  • Understanding of arrays


Difference Between Shallow and Deep Flattening

Type Description
Shallow Flatten Removes one nesting level
Deep Flatten Removes all nesting levels

Real-World Use Cases

API Responses

Sometimes APIs return nested data:

[
  ["JavaScript", "Python"],
  ["React", "Node.js"]
]

Flattening makes processing easier.


Nested menus often require flattening for searching.


E-Commerce Categories

Products may exist inside nested category trees.

Flattening helps:

  • Searching

  • Filtering

  • Recommendations


Performance Note

For small arrays:

  • Any method works fine

For very large datasets:

  • Recursive solutions may become slower

  • Built-in flat() is usually optimized

But for beginners:

  • Focus on understanding the logic first

Practice Exercise

Task 1

Flatten this array:

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

Expected Output:

[1, 2, 3, 4, 5]

Task 2

Flatten this deeply nested array:

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

Expected Output:

[1, 2, 3, 4, 5]

Nested Array Structure Diagram

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

Flatten Transformation Diagram

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

        ↓ Flatten

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

Final Thoughts

Flattening arrays is an important JavaScript skill because nested data appears everywhere in real-world applications.

The key ideas are:

  • Nested arrays contain arrays inside arrays

  • Flattening converts them into one simple array

  • flat() is the easiest solution

  • Loops and recursion help you understand the logic deeply

If you’re preparing for interviews:

  • Practice recursive flattening

  • Learn to identify nested structures

  • Focus on thinking step-by-step

Once you understand flattening, working with complex data becomes much easier.