Why not reduce?
This list intend to be a forever growing one that hope to collect typical patterns of reduce to avoid. Please feel free to suggest more examples!
This post is not about space / time performance perks by not using reduce. This is all about readability.
🔴 Do not
faces.reduce((acc, face) => {
return [...acc, mask(face)]
}, [])
✅ Do
faces.map(mask)
🔴 Do not
bags.reduce((acc, bag) => {
return [...acc, ...bag.apples]
}, [])
✅ Do
bags.flatMap(bag => bag.apples)
🔴 Do not
phones.reduce((acc, phone) => {
return isNew(phone) ? [...acc, phone] : acc
}, [])
✅ Do
phones.filter(isNew)
🔴 Do not
dogs.reduce((acc, dog) => {
return isHappy(dog) ? acc + 1 : acc
}, 0)
✅ Do
dogs.filter(isHappy).length
🔴 Do not
people.reduce((acc, person) => ({
[person.dna]: person
}), {})
✅ Do
Object.fromEntries(
people.map(person => [person.dna, person])
)
🔴 Do not
people.reduce((acc, person) => {
return Math.max(acc, person.age)
}, -Infinity)
✅ Do
Math.max(...people.map(person => person.age))