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.

JavaScriptbeginner
12 min read

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)):

javascriptjavascript
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

javascriptjavascript
const newArray = array.flatMap(callback(element, index, array), thisArg)
ParameterDescription
elementThe current element being processed
indexIndex of the current element (optional)
arrayThe original array (optional)
thisArgValue 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:

javascriptjavascript
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]
ApproachPassesIntermediate ArraysReadability
map().flat()21 (from map)Clear but verbose
flatMap()10Concise
reduce() + concat10Verbose, 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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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:

javascriptjavascript
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 Sizemap().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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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

  1. Use flatMap() when map() callbacks return arrays. If your map callback wraps results in arrays, flatMap() removes the extra nesting in a single pass.
  2. Return [] to filter, [value] to include. This pattern combines filter() and map() into one iteration.
  3. Use flat() when you only need flattening. If there is no transformation step, flat() is clearer than flatMap(x => x).
  4. Remember the one-level limit. flatMap() always flattens exactly one level. For deeper nesting, use map().flat(depth).
  5. Prefer flatMap() for performance-sensitive paths. Eliminating the intermediate array helps in hot loops and large datasets.
Rune AI

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
RunePowered by Rune AI

Frequently Asked Questions

What is the difference between flatMap() and map().flat()?

They produce identical results. flatMap() does the work in a single pass without creating an intermediate array, making it slightly faster and using less memory. Use flatMap() when your map callback returns arrays that need one level of flattening.

Can flatMap() flatten more than one level?

No. flatMap() always flattens exactly one level. If your callback returns deeply nested arrays, use `map(fn).flat(depth)` or `map(fn).flat(Infinity)` to control the flattening depth.

How do I use flatMap() to filter and transform simultaneously?

Return an empty array `[]` for elements you want to exclude and a single-element array `[transformedValue]` for elements you want to include. The empty arrays vanish during flattening, and the single-element arrays contribute their value to the result.

Does flatMap() modify the original array?

No. flatMap() returns a new array. The original array is never modified. This is consistent with [map()](/tutorials/programming-languages/javascript/how-to-use-the-javascript-array-map-method-today) and [flat()](/tutorials/programming-languages/javascript/js-array-flat-method-flatten-nested-arrays-fast), both of which are non-mutating.

When should I use reduce() instead of flatMap()?

Use [reduce()](/tutorials/programming-languages/javascript/using-the-javascript-array-reduce-method-guide) when the output is not an array (a number, object, string, etc.). Use flatMap() when the output is a flat array derived from mapping and flattening. If you find yourself building an array inside reduce(), flatMap() is usually the cleaner choice.

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.