How to filter and map an array at the same time in JavaScript
Other languages have an explicit method that both filters and maps, such as Rust’s filter_map
. In JavaScript, we have historically used reduce
to filter and map in one iteration. But now, we have another (better) choice thanks to flatMap
!
Usage of flatMap
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 20 },
{ name: 'Alice', age: 40 },
]
const over30UserNames = users.flatMap((user) => {
if (user.age >= 30) {
return user.name
}
return []
})
If you are using TypeScript, over30UserNames
is correctly inferred to be an array of strings (string[]
).
Implementing this using reduce
, we can see it requires slightly more syntax and a type annotation:
const over30UserNamesReduce = users.reduce((acc, user) => {
if (user.age >= 30) {
return [...acc, user.name]
}
return acc
}, [] as string[])
Conclusion
Next time you find yourself chaining filter
and map
, consider using flatMap
instead. It’s more performant than chaining two methods and allows TypeScript to infer the return type of the callback function, which is not the case with reduce
.