Ad space (banner)
🟨JavaScript Lessons
Lesson 43 / 69

Flattening Arrays (flatten)

In this lesson you'll use array's .flat() method so you can learn how to flatten out a nested array. This is for people searching "JavaScript flat usage" or "JavaScript array flatten."

.flat() "flattens out" arrays nested inside an array. Writing .flat(Infinity) flattens everything, no matter how deeply nested it is. Also remember that omitting the argument flattens only one level.

The sample code compares the results of .flat() (one level) versus .flat(Infinity) (everything) on a multiply-nested array, [1, [2, 3], [4, [5, 6]]]. With just one level, the inner array in [4, [5, 6]] remains unflattened — comparing the two results side by side is the point.

A common beginner stumbling block is that the default .flat() only flattens one level. For data whose nesting depth isn't known, you need to specify Infinity. Also, like other array methods, flat returns a new array — the original array isn't changed.

This method is genuinely useful in real projects — when you have nested data received from an API, or grouped data, and you want to handle it all as a single, unified list. It's also frequently used in real work for formatting API responses that contain deeply nested data.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)