Skip to main content

Command Palette

Search for a command to run...

Array Flattening in JavaScript

Understand Array Flattening in JavaScript

Published
β€’6 min read
Array Flattening in JavaScript
P

My name is 𝐏𝐫𝐚𝐀𝐚𝐬𝐑 and I talk about 𝗧𝗲𝗰𝗡-𝐊𝐧𝐨𝐰π₯𝐞𝐝𝐠𝐞, π—ͺπ—²π—―π——π—²π˜ƒ, π——π—²π˜ƒπ—’π—½π˜€ and π—Ÿπ—Άπ—³π—²π˜€π˜π˜†π—Ήπ—².

Introduction

Arrays are one of the most fundamental data structures in JavaScript. In simple cases, they store values in a single, linear structure. But as applications grow, data often becomes more complex β€” and that’s where nested arrays come into play.

Nested arrays allow us to represent hierarchical or grouped data. However, working with deeply nested structures can quickly become difficult.

This is where array flattening becomes an essential concept.

Flattening transforms a nested array into a single-level array, making it easier to process, iterate, and manipulate.

Understanding Nested Arrays

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

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

In this example:

  • The array contains numbers

  • It also contains arrays inside it

  • Those arrays can themselves contain more arrays

This creates a multi-level structure, similar to a tree.

Conceptual View

Think of it like this:

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

Each level introduces another layer of depth.

Why Flattening Matters

At first glance, nested arrays might seem harmless. But in real-world scenarios, they introduce complexity.

1. Simplifying Data Processing

Most array operations in JavaScript β€” like map, filter, and reduce β€” work best on flat arrays.

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

If you want to process all values uniformly, flattening becomes necessary:

[1, 2, 3, 4]

2. Working with API Data

APIs often return deeply nested JSON structures.

const users = [
  ["Prakash", "Rahul"],
  ["Aman", ["Riya", "Neha"]]
];

To extract meaningful data, flattening helps convert it into a usable format.

3. Cleaner Logic and Readability

Flat arrays:

  • Reduce nested loops

  • Simplify conditions

  • Improve readability

4. Real Application Use Cases

  • Rendering lists in UI frameworks

  • Data normalization before storing in databases

  • Processing logs or analytics data

  • Handling recursive structures like comments or folders

The Core Idea of Flattening

Flattening is not just a function β€” it’s a way of thinking.

At its core:

β€œIf an element is an array, break it down further. If it’s not, keep it.”

Example

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

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

Step-by-Step Thought Process

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

Take 1 β†’ keep it

Encounter [2, [3, 4]] β†’ open it

Take 2 β†’ keep it

Encounter [3, 4] β†’ open it

Take 3, 4 β†’ keep both

Take 5 β†’ keep it

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

This mental model is the foundation of all flattening techniques.

Approaches to Flatten Arrays

There are multiple ways to flatten arrays in JavaScript. Each approach reflects a different way of thinking.

1. Using flat() β€” The Built-in Method

JavaScript provides a built-in method for flattening arrays.

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

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

The number passed defines the depth.

For unknown depth:

arr.flat(Infinity);

Why It’s Useful

  • Clean and readable

  • No manual logic required

  • Ideal for everyday usage

2. Recursive Approach β€” Breaking the Problem Down

Recursion mirrors the structure of nested arrays perfectly.

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

Deep Understanding

This works because:

  • Each nested array is treated as a smaller version of the same problem

  • The function keeps calling itself until no arrays remain

This is similar to how tree traversal works.

3. Functional Approach with reduce()

This method uses a more declarative style.

function flatten(arr) {
  return arr.reduce((acc, curr) => {
    return Array.isArray(curr)
      ? acc.concat(flatten(curr))
      : acc.concat(curr);
  }, []);
}

Insight

Instead of building step-by-step manually:

  • You accumulate results

  • Combine them recursively

This approach is common in functional programming.

4. Iterative Approach Using a Stack

Recursion is elegant, but not always ideal for very deep structures.

An alternative is using a stack:

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

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

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

  return result.reverse();
}

Key Idea

  • Replace recursion with manual control

  • Use a stack to simulate depth traversal

Understanding Depth in Flattening

Not all flattening needs to be complete.

Sometimes you only want to flatten one or two levels.

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

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

This is useful when:

  • You want partial transformation

  • You want to preserve some structure

Edge Cases to Consider

Real-world data is rarely clean.

1. Empty Arrays

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

2. Mixed Data Types

[1, "text", [true, [null]]]

3. Deeply Nested Structures

[[[[[1]]]]]

4. Sparse Arrays

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

Good implementations handle all of these gracefully.

Performance Considerations

Different approaches behave differently depending on data size.

Recursion

  • Easy to write

  • May cause stack overflow for very deep arrays

Iterative (Stack)

  • More control

  • Safer for large data

flat()

  • Optimized internally

  • Best for most practical use cases

Conceptual Connection

Flattening is more than just an array problem.

It connects to:

  • Tree traversal

  • Recursion patterns

  • Depth-first search

  • Data transformation pipelines

Understanding flattening deeply strengthens your ability to solve complex problems.

Final Thoughts

Array flattening might look like a small utility problem, but it teaches an important lesson:

Complex structures can often be simplified by breaking them down step by step.

Once you understand the idea of:

  • Identifying structure

  • Decomposing it

  • Rebuilding it

You unlock a powerful way of thinking that applies far beyond arrays.


I write articles on blog.prakashtsx.com and also post development-related content on:

JavaScript

Part 1 of 11

In this series of blogs I have written some interesting concepts related to JavaScript.

Up next

Template Literals in JavaScript

Improve readability with Template Literals

More from this blog

Learn with Prakash

36 posts

My name is 𝐏𝐫𝐚𝐀𝐚𝐬𝐑 and I talk about 𝗧𝗲𝗰𝗡-𝐊𝐧𝐨𝐰π₯𝐞𝐝𝐠𝐞, π—ͺπ—²π—―π——π—²π˜ƒ, π——π—²π˜ƒπ—’π—½π˜€ and π—Ÿπ—Άπ—³π—²π˜€π˜π˜†π—Ήπ—².