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

Practical flatMap() Use Cases

Explore common scenarios like splitting strings into words, expanding nested data, and filtering with expansion.

Practical flatMap() Use Cases

You'll learn real-world scenarios where flatMap() shines: splitting strings, expanding nested data, and filtering with expansion.

Now that you understand flatMap() and when to use it versus map().flat(), let's explore concrete situations where it becomes your go-to tool.

Splitting Strings into Words

One common use case is taking an array of sentences and expanding them into individual words:

const sentences = ["Hello world", "flatMap is useful", "JavaScript rocks"];

const words = sentences.flatMap(sentence => sentence.split(" "));
// ["Hello", "world", "flatMap", "is", "useful", "JavaScript", "rocks"]

Each sentence maps to an array of words, and flatMap() automatically flattens the result into one list.

Expanding Nested Data

When working with objects that contain arrays, flatMap() helps extract and expand:

const users = [
  { name: "Alice", skills: ["JavaScript", "CSS"] },
  { name: "Bob", skills: ["Python"] }
];

const allSkills = users.flatMap(user => user.skills);
// ["JavaScript", "CSS", "Python"]

Instead of getting nested arrays, you get one flat list of all skills.

Filtering with Expansion

You can combine filtering and mapping in one operation. Return an empty array to filter out items:

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

const doubled = numbers.flatMap(n => n % 2 === 0 ? [n * 2] : []);
// [4, 8] — only even numbers, doubled

This is more elegant than chaining .filter().map() for certain patterns.

Key Takeaway: Use flatMap() when you need to split strings into arrays, extract items from nested structures, or simultaneously filter and expand data—it handles the mapping and flattening in one efficient step.