0 day streak
javascript / intermediate
Snippet

Efficient Data Extraction with flatMap

flatMap combines mapping and flattening into a single pass. It is particularly useful when you need to extract nested arrays from a list of objects and want a single, flat result list.

snippet.js
javascript
1
2
3
4
5
6
7
8
const posts = [
{ id: 1, tags: ['js', 'web'] },
{ id: 2, tags: ['nextjs'] },
{ id: 3, tags: ['react', 'web'] }
];
const allUniqueTags = [...new Set(posts.flatMap(p => p.tags))];
// Result: ['js', 'web', 'nextjs', 'react']
nextjs
Breakdown
1
posts.flatMap(p => p.tags)
Maps over each post and flattens the resulting arrays into one level.
2
...new Set(...)
A common pattern to remove duplicate values from an array.