Back to blog
JavaScript

Array Flatten in JavaScript

May 10, 2026 4 min read

What Are Nested Arrays?

A nested array is an array that contains other arrays inside it.


Example of a Nested Array

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


Visual Representation

Diagram: flowchart TD

More Deeply Nested Example

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


Visual Structure

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


What Does Flattening Mean?

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


Example

Before Flattening

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


After Flattening

[1, 2, 3, 4, 5]


Flatten Transformation Visual

flowchart LR
    A[[1, [2,3], [4,5]]] --> B[[1,2,3,4,5]]


Why Flattening Arrays Is Useful

Flattening is commonly used in:

  • API response processing

  • Tree data transformation

  • Menu structures

  • Category systems

  • Data normalization

  • Search indexing


Real-World Example

Imagine an e-commerce category structure.

const categories = [
  ["Phones", "Laptops"],
  ["Shoes", "Shirts"],
  ["Books"]
];

You may want a single searchable list:

["Phones", "Laptops", "Shoes", "Shirts", "Books"]


Understanding the Problem Step by Step

Input

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


Goal

[1, 2, 3, 4, 5]


Step-by-Step Thinking

Step 1

Take first value:

1

Already a normal value.

Add it directly.


Step 2

Take second value:

[2, 3]

This is an array.

Open it and extract values.


Step 3

Take third value:

[4, 5]

Again, extract inner values.


Final Result

[1, 2, 3, 4, 5]


Approach 1: Using flat()

This is the easiest modern JavaScript solution.


Example

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

const flattened = numbers.flat();

console.log(flattened);


Output

[1, 2, 3, 4, 5]


How flat() Works

flat() removes one nesting level by default.


One-Level Flattening

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

console.log(data.flat());


Output

[1, 2, [3, 4]]

Notice:

[3, 4]

still remains nested.


Flattening Multiple Levels

You can specify depth.


Example

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

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


Output

[1, 2, 3, 4]


Visualizing Depth Flattening

flowchart TD
    A[[1,[2,[3,4]]]]
    A --> B[flat 1 level]
    B --> C[[1,2,[3,4]]]
    C --> D[flat another level]
    D --> E[[1,2,3,4]]


Approach 2: Using Infinity Depth

Useful when nesting depth is unknown.


Example

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

const flattened = data.flat(Infinity);

console.log(flattened);


Output

[1, 2, 3, 4, 5]


Approach 3: Using reduce()

This is common in interviews.


Example

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

const flattened = numbers.reduce((accumulator, currentValue) => {
  return accumulator.concat(currentValue);
}, []);

console.log(flattened);


Output

[1, 2, 3, 4, 5]


Step-by-Step reduce() Explanation

Initial Value

[]


First Iteration

[] + 1

Result:

[1]


Second Iteration

[1] + [2,3]

Result:

[1,2,3]


Third Iteration

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

Result:

[1,2,3,4,5]


Approach 4: Using Loops

Important for understanding problem-solving logic.


Example

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

const result = [];

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

console.log(result);


Output

[1, 2, 3, 4, 5]


Why Learn the Loop Version?

Because interviews often test:

  • Logic building

  • Understanding nested structures

  • Problem-solving ability

Not just memorizing methods.


Common Interview Scenario

Problem

Flatten deeply nested arrays without using flat().


Recursive Solution

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

  for (let item of array) {
    if (Array.isArray(item)) {
      result = result.concat(flattenArray(item));
    } else {
      result.push(item);
    }
  }

  return result;
}

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

console.log(flattenArray(numbers));


Output

[1, 2, 3, 4, 5]


How Recursive Flattening Works

flowchart TD
    A[[1,[2,[3,[4,5]]]]]
    A --> B[Check item]
    B --> C{Is Array?}

    C -->|Yes| D[Call flattenArray again]
    C -->|No| E[Push to result]

    D --> B


Important Method Used

Array.isArray()

Checks whether a value is an array.


Example

console.log(Array.isArray([1, 2]));
console.log(Array.isArray(10));


Output

true
false


Comparison of Approaches

ApproachEasy to LearnSupports Deep NestingInterview Friendly
flat()YesYesModerate
reduce()ModerateNoGood
LoopsModerateNoVery Good
RecursionAdvanced BeginnerYesExcellent

Common Beginner Mistakes

1. Forgetting Nested Arrays Exist

Incorrect assumption:

All values are direct values


2. Confusing flat() Depth

array.flat()

only removes one level.


3. Not Checking Array Type

Always verify:

Array.isArray(value)


Real-World API Example

API responses often contain nested data.


Example

const apiResponse = [
  ["Laptop", "Phone"],
  ["Keyboard"],
  ["Mouse", "Monitor"]
];

const products = apiResponse.flat();

console.log(products);


Output

[ 'Laptop', 'Phone', 'Keyboard', 'Mouse', 'Monitor' ]


Practice Exercises

Exercise 1

Flatten this array:

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


Exercise 2

Flatten deeply nested arrays:

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


Exercise 3

Write your own recursive flatten function.


Key Takeaways

ConceptSummary
Nested ArraysArrays inside arrays
FlatteningConverting nested arrays into one level
flat()Modern built-in flatten method
flat(Infinity)Removes all nesting
reduce()Common interview solution
RecursionBest for deep nesting problems

Final Notes

Flattening arrays is an important JavaScript skill because it teaches:

  • Nested data handling

  • Array transformation

  • Recursion

  • Problem-solving

  • Data normalization

These concepts appear frequently in:

  • Frontend development

  • Backend APIs

  • Interview questions

  • Real-world applications


0 Comments

Sign in to join the conversation

No comments yet. Be the first to comment!