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

Transforming and Flattening at Once with flatMap()

In this lesson you'll use array's .flatMap() method so you can learn how to combine transforming and flattening into a single step. This is for people searching "JavaScript flatMap usage."

.flatMap() is a method that combines the "transform with .map(), then flatten one level with .flat()" process into a single step. It's handy when "you want to turn one element into several elements." It's shorter than writing .map().flat(), and it also communicates the intent more clearly.

The sample code converts an array containing several sentences into a single list of individual words with .flatMap((s) => s.split(" ")), and converts a numeric array into a new array containing "the original value and its double" with .flatMap((n) => [n, n * 2]). The idea of producing multiple elements from one element is what sets it apart from an ordinary map.

A common beginner stumbling block is choosing between .flatMap() and .map(). If you're only converting one element into one value, map is enough — but if you want to produce multiple elements (an array) from a single element, you need flatMap. Look carefully at what you're trying to do and choose the right method.

This can clean up your code nicely in situations where you want to transform and expand at the same time, such as breaking sentences into individual words and gathering them into a single list. It's one of the methods that lets you keep making array-handling code shorter and shorter — genuinely useful in real projects.

JavaScript
OUTPUT

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

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