flatMap()
flatMap<
T,Result>(collection,iteratee):Result[]
Creates a flattened array of values by running each element in collection thru iteratee and flattening the mapped results.
💎 Why is this a Hidden Gem?
Combine mapping and flattening in a single, expressive operation.
Use array.flatMap() directly instead.
Type Parameters
T: T
The type of elements in the collection.
Result: Result
The type of elements in the result.
Parameters
collection: readonly T[]
The collection to iterate over.
iteratee: (value, index, collection) => Result | readonly Result[]
The function invoked per iteration.
Returns: Result[]
The new flattened array.
See Also
Since
2.0.0
Also known as
chain (Ramda) · flatMap (Lodash, es-toolkit, Remeda, Effect) · ❌ (Radashi, Modern Dash, Antfu)
Example
// ❌ Deprecated approach
flatMap([1, 2], n => [n, n]);
// => [1, 1, 2, 2]
// ✅ Recommended approach
[1, 2].flatMap(n => [n, n]);
// => [1, 1, 2, 2]
How it works?
Maps and flattens result by one level.
Deprecated: Use array.flatMap() directly (ES2019).
Native Equivalent
// ❌ flatMap(arr, fn)
// ✅ arr.flatMap(fn)
Use Cases
Map and flatten in one step 📌
Transform elements and flatten the result.
const users = [{ tags: ["a", "b"] }, { tags: ["c"] }];
users.flatMap(u => u.tags);
// => ["a", "b", "c"]
Expand items
Generate multiple items from each source item.
const nums = [1, 2, 3];
nums.flatMap(n => [n, n * 10]);
// => [1, 10, 2, 20, 3, 30]
Filter and transform
Combine filtering and mapping.
const items = [1, 2, 3, 4, 5];
items.flatMap(n => n > 2 ? [n * 2] : []);
// => [6, 8, 10]
Extract all tags from a collection of articles
Collect all tags across multiple articles into a single flat array. Common pattern for building tag clouds, filters, or category indexes in CMS/blog systems.
const articles = [
{ title: "Intro to TS", tags: ["typescript", "javascript", "tutorial"] },
{ title: "React Hooks", tags: ["react", "javascript", "hooks"] },
{ title: "Node.js API", tags: ["nodejs", "javascript", "backend"] },
];
const allTags = flatMap(articles, (a) => a.tags);
// => ["typescript", "javascript", "tutorial", "react", "javascript", "hooks", "nodejs", "javascript", "backend"]
// Combine with uniq for unique tags
const uniqueTags = uniq(allTags);
// => ["typescript", "javascript", "tutorial", "react", "hooks", "nodejs", "backend"]