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);
Totally! And that is also much more readable!
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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?
Totally! And that is also much more readable!