David Tu
David Tu

Reputation: 47

Is there a way to use .reduce() on an array of objects?

I want to add all the items I have in my JavaScript array together * the item quantity. I have an array of objects like so:

var products = [ {price: 1, quantity: 2},
                  {price: 4, quantity: 1},
                  {price: 2, quantity: 1} ]

Right now I'm using

var sum = 0;
products.forEach(function(item){
  sum += item.price * item.quantity;
})
return sum;

Which works, but I'm just wondering if I can refactor this using .reduce(). So far I haven't had any luck as I've tried mapping it out and reducing it as well. Is it possible to do this with reduce?

Upvotes: 1

Views: 5815

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382274

Of course, it's the most standard use case of reduce:

var sum = products.reduce((sum, p) => sum + p.price*p.quantity, 0);

Upvotes: 10

Related Questions