The Array.prototype.flatMap() Method
What you'll learn: How flatMap() combines mapping and flattening in one efficient operation.
The Core Idea
Imagine you have an array and you want to transform each element, but some transformations produce multiple values. You could use map() and then flat(), but flatMap() does both in one step—it's like a shortcut that maps your data and automatically flattens the result by one level.
Think of it like unpacking boxes: you transform each item into a new box (which might contain multiple things), and flatMap() automatically unpacks those boxes for you.
How It Works
flatMap() takes a callback function just like map(), but it expects that function might return an array. After mapping, it flattens the result by one level:
const numbers = [1, 2, 3];
// Using map + flat separately
const resultA = numbers.map(n => [n, n * 2]).flat();
console.log(resultA); // [1, 2, 2, 4, 3, 6]
// Using flatMap - same result, cleaner
const resultB = numbers.flatMap(n => [n, n * 2]);
console.log(resultB); // [1, 2, 2, 4, 3, 6]
Common Use Cases
Perfect for when you need to expand or conditionally include items:
const sentences = ["Hello world", "FlatMap rocks"];
// Split each sentence into words
const words = sentences.flatMap(s => s.split(' '));
console.log(words); // ["Hello", "world", "FlatMap", "rocks"]
// Conditional inclusion (return empty array to exclude)
const nums = [1, 2, 3, 4];
const evensDoubled = nums.flatMap(n => n % 2 === 0 ? [n * 2] : []);
console.log(evensDoubled); // [4, 8]
Key Takeaway: flatMap() is equivalent to map().flat(1)—use it when your mapping function produces multiple values per input element, saving you an extra method call and making your code more expressive.