Skip to main content

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.

DEPRECATED

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"]