JavaScript Array flatMap Method: Complete Guide
Master the JavaScript flatMap() method for mapping and flattening arrays in a single pass. Covers syntax, comparison with map().flat(), real-world transformation patterns, conditional filtering, performance, and common mistakes.
The flatMap() method applies a function to every element in an array and then flattens the result by one level. It combines the work of map() and flat() into a single call that is both more readable and more efficient. Whenever your map() callback returns arrays that need flattening, flatMap() is the cleaner tool.
What flatMap() Does
flatMap() calls your callback on each element (like map()), then flattens the collected results by exactly one level (like flat(1)):
const sentences = ["Hello world", "Good morning"];
// map() produces nested arrays
const nested = sentences.map(s => s.split(" "));
console.log(nested); // [["Hello", "world"], ["Good", "morning"]]
// flatMap() maps AND flattens in one step
const words = sentences.flatMap(s => s.split(" "));
console.log(words); // ["Hello", "world", "Good", "morning"]Syntax
const newArray = array.flatMap(callback(element, index, array), thisArg)| Parameter | Description |
|---|---|
element | The current element being processed |
index | Index of the current element (optional) |
array | The original array (optional) |
thisArg | Value to use as this inside the callback (optional) |
Return Value
A new array formed by applying the callback to each element and then flattening the result by one level. The original array is never modified.
flatMap() vs map().flat()
flatMap() is equivalent to map().flat() but does both operations in a single pass:
const data = [1, 2, 3, 4];
// Two-pass: map creates intermediate array, flat creates final array
const twoPass = data.map(n => [n, n * 2]).flat();
// One-pass: flatMap creates only the final array
const onePass = data.flatMap(n => [n, n * 2]);
// Both produce: [1, 2, 2, 4, 3, 6, 4, 8]| Approach | Passes | Intermediate Arrays | Readability |
|---|---|---|---|
map().flat() | 2 | 1 (from map) | Clear but verbose |
flatMap() | 1 | 0 | Concise |
| reduce() + concat | 1 | 0 | Verbose, harder to read |
flatMap Flattens One Level Only
flatMap() always flattens exactly one level. If your callback returns deeply nested arrays and you need them fully flat, use map().flat(depth) or map().flat(Infinity) instead. flatMap() has no depth parameter.
Basic Examples
Duplicating Elements
const numbers = [1, 2, 3];
const doubled = numbers.flatMap(n => [n, n]);
console.log(doubled); // [1, 1, 2, 2, 3, 3]Adding Separators Between Elements
const items = ["Home", "Products", "Contact"];
const withSeparators = items.flatMap((item, index) =>
index < items.length - 1 ? [item, "|"] : [item]
);
console.log(withSeparators); // ["Home", "|", "Products", "|", "Contact"]Splitting and Transforming
const csvRows = [
"Alice,Engineering,95000",
"Bob,Marketing,72000",
"Carol,Engineering,110000",
];
const cells = csvRows.flatMap(row => row.split(","));
console.log(cells);
// ["Alice", "Engineering", "95000", "Bob", "Marketing", "72000", "Carol", "Engineering", "110000"]Filtering and Mapping in One Step
One of flatMap()'s most powerful patterns is simultaneous filtering and mapping. Return an empty array [] to exclude an element, or a single-element array [value] to include a transformed result:
const users = [
{ name: "Alice", role: "admin", active: true },
{ name: "Bob", role: "user", active: false },
{ name: "Carol", role: "admin", active: true },
{ name: "Dave", role: "user", active: true },
];
// Filter active admins AND extract their names in one pass
const activeAdminNames = users.flatMap(user =>
user.role === "admin" && user.active ? [user.name] : []
);
console.log(activeAdminNames); // ["Alice", "Carol"]
// Equivalent two-pass approach
const twoPass = users
.filter(u => u.role === "admin" && u.active)
.map(u => u.name);This pattern replaces the common filter() + map() chain with a single iteration:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// flatMap: filter even numbers and double them in one pass
const evenDoubled = numbers.flatMap(n =>
n % 2 === 0 ? [n * 2] : []
);
console.log(evenDoubled); // [4, 8, 12, 16, 20]Real-World Patterns
Extracting Nested Collections
const orders = [
{ id: "ORD-1", items: [{ name: "Laptop", qty: 1 }, { name: "Cable", qty: 3 }] },
{ id: "ORD-2", items: [{ name: "Mouse", qty: 2 }] },
{ id: "ORD-3", items: [{ name: "Monitor", qty: 1 }, { name: "Stand", qty: 1 }] },
];
const allItems = orders.flatMap(order =>
order.items.map(item => ({
orderId: order.id,
...item,
}))
);
console.log(allItems);
// [
// { orderId: "ORD-1", name: "Laptop", qty: 1 },
// { orderId: "ORD-1", name: "Cable", qty: 3 },
// { orderId: "ORD-2", name: "Mouse", qty: 2 },
// { orderId: "ORD-3", name: "Monitor", qty: 1 },
// { orderId: "ORD-3", name: "Stand", qty: 1 },
// ]Expanding Ranges
const ranges = [
{ start: 1, end: 3 },
{ start: 10, end: 12 },
{ start: 20, end: 21 },
];
const expanded = ranges.flatMap(range => {
const result = [];
for (let i = range.start; i <= range.end; i++) {
result.push(i);
}
return result;
});
console.log(expanded); // [1, 2, 3, 10, 11, 12, 20, 21]Parsing Multi-Value Fields
const employees = [
{ name: "Alice", skills: "JavaScript, TypeScript, React" },
{ name: "Bob", skills: "Python, Django" },
{ name: "Carol", skills: "JavaScript, Node.js, PostgreSQL" },
];
const allSkills = [...new Set(
employees.flatMap(emp => emp.skills.split(", "))
)];
console.log(allSkills);
// ["JavaScript", "TypeScript", "React", "Python", "Django", "Node.js", "PostgreSQL"]Generating Test Data
const colors = ["red", "blue"];
const sizes = ["S", "M", "L"];
const combinations = colors.flatMap(color =>
sizes.map(size => ({ color, size }))
);
console.log(combinations);
// [
// { color: "red", size: "S" }, { color: "red", size: "M" }, { color: "red", size: "L" },
// { color: "blue", size: "S" }, { color: "blue", size: "M" }, { color: "blue", size: "L" },
// ]Conditional Expansion
const notifications = [
{ type: "email", addresses: ["alice@ex.com", "admin@ex.com"] },
{ type: "sms", addresses: [] },
{ type: "email", addresses: ["bob@ex.com"] },
];
// Only expand non-empty notification targets
const targets = notifications.flatMap(notif =>
notif.addresses.length > 0
? notif.addresses.map(addr => ({ type: notif.type, to: addr }))
: []
);
console.log(targets);
// [
// { type: "email", to: "alice@ex.com" },
// { type: "email", to: "admin@ex.com" },
// { type: "email", to: "bob@ex.com" },
// ]Performance Considerations
flatMap() is more efficient than map().flat() because it avoids creating an intermediate array:
const data = Array.from({ length: 100000 }, (_, i) => i);
// Two-pass: creates a 100K intermediate array, then flattens
console.time("map+flat");
data.map(n => [n, n * 2]).flat();
console.timeEnd("map+flat"); // ~15-25ms
// One-pass: no intermediate array
console.time("flatMap");
data.flatMap(n => [n, n * 2]);
console.timeEnd("flatMap"); // ~10-18ms| Array Size | map().flat() | flatMap() | Savings |
|---|---|---|---|
| 1,000 | ~0.5ms | ~0.3ms | ~40% |
| 100,000 | ~20ms | ~12ms | ~40% |
| 1,000,000 | ~200ms | ~120ms | ~40% |
The savings come from skipping the intermediate array allocation and garbage collection cycle.
Common Mistakes
Expecting deep flattening:
const data = [1, 2, 3];
// flatMap flattens ONE level only
const result = data.flatMap(n => [[n, n * 2]]);
console.log(result); // [[1, 2], [2, 4], [3, 6]] — still nested!
// If you need deeper flattening, chain .flat(depth):
const deep = data.map(n => [[n, n * 2]]).flat(2);
console.log(deep); // [1, 2, 2, 4, 3, 6]Returning non-array values from the callback:
const nums = [1, 2, 3];
// This works but defeats the purpose of flatMap
const result = nums.flatMap(n => n * 2);
console.log(result); // [2, 4, 6] — same as map()
// flatMap shines when the callback returns arrays
const pairs = nums.flatMap(n => [n, n * 2]);
console.log(pairs); // [1, 2, 2, 4, 3, 6]Forgetting the empty array for filtering:
const values = [1, -2, 3, -4, 5];
// Bug: returning undefined for filtered items
const positive = values.flatMap(n => n > 0 ? n : undefined);
console.log(positive); // [1, undefined, 3, undefined, 5]
// Fix: return empty array to exclude
const positive2 = values.flatMap(n => n > 0 ? [n] : []);
console.log(positive2); // [1, 3, 5]Using flatMap when flat() or map() would suffice:
const nested = [[1, 2], [3, 4]];
// Overcomplicated: flatMap that just returns each element
const flat = nested.flatMap(arr => arr);
// Simpler: just use flat()
const flat2 = nested.flat();
// Both produce: [1, 2, 3, 4]Best Practices
- Use flatMap() when map() callbacks return arrays. If your map callback wraps results in arrays, flatMap() removes the extra nesting in a single pass.
- Return
[]to filter,[value]to include. This pattern combines filter() and map() into one iteration. - Use flat() when you only need flattening. If there is no transformation step,
flat()is clearer thanflatMap(x => x). - Remember the one-level limit. flatMap() always flattens exactly one level. For deeper nesting, use
map().flat(depth). - Prefer flatMap() for performance-sensitive paths. Eliminating the intermediate array helps in hot loops and large datasets.
Rune AI
Key Insights
- Map and flatten in one pass: flatMap() combines map() and flat(1) without intermediate arrays
- Filter-map pattern: return [] to exclude, [value] to include and transform in one iteration
- One level only: flatMap() always flattens exactly one level with no depth parameter
- Non-mutating: returns a new array, leaving the original unchanged
- Better performance: ~40% faster than map().flat() by avoiding intermediate array allocation
Frequently Asked Questions
What is the difference between flatMap() and map().flat()?
Can flatMap() flatten more than one level?
How do I use flatMap() to filter and transform simultaneously?
Does flatMap() modify the original array?
When should I use reduce() instead of flatMap()?
Conclusion
The flatMap() method is JavaScript's tool for one-step map-and-flatten operations. It produces cleaner code and better performance than map().flat() by eliminating the intermediate array. Its most powerful pattern is returning [] to exclude elements and [value] to include them, effectively combining filter() and map() into a single pass. The critical limitation is that it only flattens one level. For deeper nesting, chain map() with flat(depth), and for simple non-transforming flattening, use flat() directly.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.