Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Published
5 min read
Array Flatten in JavaScript

Overview

When working with JavaScript, you’ll often encounter data that isn’t neatly structured. Instead of a simple list, you might get arrays inside arrays—sometimes even deeply nested.

What is a nested array?

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

JavaScript allows arrays to store any type of value—including other arrays—so you can create multi-level data structures.

Example:

const arr = [
  [1,  2,  3,  4,  5],
  [6,  7,  8,  9, 10],
  [11, 12, 13, 14, 15],
  [16, 17, 18, 19, 20]
];

console.log(arr);

Why do developers flatten an array?

Flattening an array in JavaScript means converting a nested array (an array inside an array) into a single-level array.

In real-world data, it often comes from an API in a complex array format. To perform search and query operations, developers often need to flatten the array, which makes some operations easier.

Example

Imagine you are building an e-commerce app.

const playlists = [
  {
    name: "Workout",
    songs: ["Track A", "Track B"]
  },
  {
    name: "Chill",
    songs: ["Track C"]
  },
  {
    name: "Travel",
    songs: ["Track D", "Track E"]
  }
];

Problem:

You want a list of all products sold. Right now, it's nested:

[
  ["Track A", "Track B"],
  ["Track C"],
  ["Track D", "Track E"]
]

Solution: Flatten the array

const allSongs = playlists.map(p => p.songs).flat();

console.log(allSongs);
// ["Track A", "Track B", "Track C", "Track D", "Track E"]

Why Flattening is Important

1. Makes Data Easier to Process

Most array methods like .map(), .filter(), and .reduce() work best on flat arrays.

Without Flattening

const items = [
  ["Pen", "Pencil"],
  ["Book", "Notebook"]
];

const result = items.map(group =>
  group.filter(i => i.includes("P"))
);

console.log(result);
// [["Pen", "Pencil"], []]

Still nested. Not very useful.

With Flattening

const result = items
  .flat()
  .filter(i => i.includes("P"));

console.log(result);
// ["Pen", "Pencil"]

Cleaner and easier.

2. Searching Becomes Simple

Searching nested structures requires loops inside loops.

Flattening removes that complexity.

const products = [["TV"], ["Laptop", "Camera"], ["Phone"]];

const flatProducts = products.flat();

console.log(flatProducts.includes("Camera"));
// true

3. Useful for Calculations

Math operations are easier on flat arrays.

const expenses = [[200, 300], [150], [400, 50]];

const total = expenses
  .flat()
  .reduce((sum, val) => sum + val, 0);

console.log(total);
// 1100

Types of Flattening

1. Shallow Flattening

Removes only one level of nesting.

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

console.log(arr.flat());
// [1, 2, 3, 4, [5]]

2. Deep Flattening

Removes all levels of nesting.

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

console.log(arr.flat(Infinity));
// [1, 2, 3, 4]

Different Ways to Flatten Arrays

1. Using Array.flat() (Modern Approach)

This is the easiest and most readable way.

const values = [1, [2, [3]]];

console.log(values.flat());        // [1, 2, [3]]
console.log(values.flat(2));       // [1, 2, 3]
console.log(values.flat(Infinity));// [1, 2, 3]

Why use Infinity?

Because you don’t need to worry about depth—it flattens everything.

2. Using Recursion (Classic Interview Method)

This approach shows your understanding of logic.

function flatten(input) {
  let output = [];

  for (let element of input) {
    if (Array.isArray(element)) {
      output = output.concat(flatten(element));
    } else {
      output.push(element);
    }
  }

  return output;
}

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

How This Works (Simple Explanation)

  • Loop through each item

  • If it's an array → call the function again

  • If it's a value → store it

  • Combine everything

This continues until all nested levels are processed.

Flattening isn’t just a concept—it appears in real interview questions.

1. Nested Messages System

const threads = [
  {
    text: "Hello",
    replies: [
      {
        text: "Hi",
        replies: [
          { text: "How are you?" }
        ]
      }
    ]
  }
];

Goal

["Hello", "Hi", "How are you?"]

Solution

function extractMessages(list) {
  let result = [];

  for (let item of list) {
    result.push(item.text);
    if (item.replies) {
      result = result.concat(extractMessages(item.replies));
    }
  }

  return result;
}

2. Folder Structure Problem

const drive = {
  files: ["doc1.pdf"],
  folders: [
    {
      files: ["image.png"],
      folders: []
    }
  ]
};

Goal

["doc1.pdf", "image.png"]

3. Category Tree

const catalog = [
  {
    title: "Clothing",
    sub: [
      { title: "Men", sub: [] },
      { title: "Women", sub: [] }
    ]
  }
];

Output

["Clothing", "Men", "Women"]

4. Classic Flatten Problem

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

Output

[1, 2, 3, 4, 5]

Key Takeaways

  • Nested arrays are common in real-world data

  • Flattening converts complex structures into simple lists

  • flat() It is the easiest method for modern JavaScript

  • Recursion is important for interviews and a deep understanding

  • Flattening improves:

    • readability

    • performance

    • maintainability

Final Thoughts

Once you understand flattening, you’ll start noticing how often it appears in real applications—APIs, databases, UI data, everywhere.

It’s not just a method—it’s a way of simplifying complexity.

Master it once, and you’ll use it everywhere.