[Solved] Whats the best way to get the total from the cart? [closed]


Your attempt is close, but doesn’t work because your price and amount values are strings (that is, they’re encased in quotes). Now, if you had instantiated your total variable to 0, the code would then realize you want price and amount to be added as a number, and work as you expect:

var cart = [ { itemid: '572462', name: 'item1', amount: '1', price: '499' },
  { itemid: '572458', name: 'Item2', amount: '1', price: '699' } ];

var total = 0;
for (let i = 0; i < cart.length; i++) {
  total += cart[i].price * cart[i].amount;
}
console.log(total);

Personally, I prefer to use .reduce() to do this sort of thing.

var items = [ { itemid: '572462', name: 'item1', amount: '1', price: '499' },
  { itemid: '572458', name: 'Item2', amount: '1', price: '699' } ]
  
var total = items.reduce((total, item) => total + (+item.price * +item.amount), 0);

console.log(total);

.reduce() works by looping through each item within an array and modifying an “accumulator”. The accumulator is the value that will eventually be returned. For example, if you were trying to sum the items of an array, you’d do accummulator + currentItem. At the end, your accumulator would be the sum of all the numbers.

Note that I’ve prefixed your item.price and item.amount with a unary + operator, so that string values ("699") would instead be converted to integers (699) before combining them.

5

solved Whats the best way to get the total from the cart? [closed]