Course contentsShow
← JavaScript
Lesson 886 of 2,72320. Array Iteration and TransformationFree lesson

Flattening Multi-Dimensional Arrays

Practice flattening arrays with varying nesting depths, including using Infinity to flatten completely.

Flattening Multi-Dimensional Arrays

What you'll learn: How to flatten arrays with different nesting depths, including completely flattening arrays of any depth using Infinity.

The Core Idea

In the previous lesson, you learned about flat() with a specific depth. Now let's explore how to handle arrays with varying nesting levels—sometimes you don't know how deeply nested your data is, or you want to flatten everything regardless of depth.

The flat() method accepts a depth parameter that tells it how many levels deep to flatten. Here's the key insight: you can pass Infinity as the depth to flatten completely, no matter how many levels exist.

Different Flattening Depths

const shallow = [1, [2, 3], 4];
console.log(shallow.flat(1));
// [1, 2, 3, 4]

const deeper = [1, [2, [3, 4]], 5];
console.log(deeper.flat(1));
// [1, 2, [3, 4], 5] — only one level flattened

console.log(deeper.flat(2));
// [1, 2, 3, 4, 5] — two levels flattened

Flattening Completely with Infinity

When you have unpredictably nested arrays:

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

console.log(messyData.flat(Infinity));
// [1, 2, 3, 4, 5, 6, 7] — completely flattened!

Think of Infinity as saying "keep flattening until there's nothing left to flatten." It's like peeling an onion with unlimited layers until you reach only individual pieces.

Practical Use Cases

This is especially useful when processing data structures where nesting depth varies, like comment threads, nested menu items, or hierarchical categories that need to be converted to a simple list.

Key Takeaway: Use flat(Infinity) to completely flatten an array of any nesting depth—perfect when you need a simple, one-dimensional result from complex, nested data.