Arina S.
Arina S.

Reputation: 123

How to count the sum of values in an array of objects in JavaScript?

It's such an easy task, but somehow I'm stuck. I have an array of objects of product items that looks like this:

[{id: 1, price: 30, quantity: 2}, {id: 2, price: 20, quantity: 4}, {id: 3, price: 10, quantity: 2}]

I need to count the total price of all items, which should be: the price of a specific product multiplied by quantity and the same for previous products. Example: (30*2)+(20*4)+(10*2)

My code looks like this:

    items.forEach(function (item) {
           let sum = item.price * item.quantity;
           console.log(sum);
});

The output looks like:

60
80
20

But I need to count the total which should be 160 and render it to the page and somehow I can't figure out the way to do that

Upvotes: 2

Views: 10621

Answers (5)

Mohammad Faisal
Mohammad Faisal

Reputation: 2392

let items = [
  {id: 1, price: 30, quantity: 2}, 
  {id: 2, price: 20, quantity: 4}, 
  {id: 3, price: 10, quantity: 2}
]

let total = items.reduce((sum,item) => sum + item.price * item.quantity, 0);

console.log(total);

Upvotes: 2

Kevin
Kevin

Reputation: 451

The Array.prototype.reduce() method is best suited for operations like this (sum total).

In my answer below, sum is the accumulator and is initially set to 0. The accumulator is the value previously returned by the callback. The { price, quantity } is object destructering of the current value.

const sumTotal = arr =>
  arr.reduce((sum, { price, quantity }) => sum + price * quantity, 0)

const data = [
  { id: 1, price: 30, quantity: 2 },
  { id: 2, price: 20, quantity: 4 },
  { id: 3, price: 10, quantity: 2 },
]

const total = sumTotal(data)

console.log(total) // 160

Here is a similar example.

Upvotes: 11

Pococapace
Pococapace

Reputation: 19

If you can use an external library, I suggest using the sumBy method from lodash library

Example:

_.sumBy(items, function(item) { return item.price * item.quantity; });

Upvotes: 0

Zulqarnain Jalil
Zulqarnain Jalil

Reputation: 1681

var products =[{id: 1, price: 30, quantity: 2}, {id: 2, price: 20, quantity: 4}, {id: 3, price: 10, quantity: 2}]
console.log(products.map(x=> x.price*x.quantity).reduce((a, b) => a + b, 0))

Upvotes: 0

Damien
Damien

Reputation: 1600

You are close to getting the answer. I modified slightly your code and get the expected result. See below.

const items = [{id: 1, price: 30, quantity: 2}, {id: 2, price: 20, quantity: 4}, {id: 3, price: 10, quantity: 2}];

const sumItems = () => {
let sum = 0;
items.forEach(function(item) {
    let calculation = item.price * item.quantity;
    sum += calculation;
})
console.log(sum);
};

sumItems();

Upvotes: 3

Related Questions