DEV Community

Discussion on: You don't need Array.reduce()

Collapse
 
conaxliu profile image
ConaxLiu • Edited

I haven't seen any mention of forEach in this thread. So I wonder why do we still need reduce when forEach can achieve exactly the same result and number of code lines?

var trips = [{type: 'car', dist: 42}, {type: 'foot', dist: 3}, {type:'flight', dist: 212}, {type: 'car', dist: 90}, {type: 'foot', dist: 7}] 

var distanceByType = {};

trips.forEach(curr => {
    const { type, dist } = curr;
    if (distanceByType[type]) {
        distanceByType[type] += dist;
    } else {
        distanceByType[type] = dist;
    }
});

console.log(distanceByType);
Collapse
 
trusktr profile image
Joe Pea

Totally! And that is also much more readable!