-9

I currently have the cart stored like this:

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

Whats the best way to loop through the cart and get the total price with amount * price? I cant quite figure it out...

Current code:

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

this console.log always give me a NaN

DoubleJ
  • 117
  • 1
  • 11
  • What have you tried? Information about how to loop through an array is quite readily available. – TypeIA Aug 13 '18 at 19:54
  • Show us the code you are using so we can help out. – justDan Aug 13 '18 at 19:55
  • Well I know, but everything I tried already didn't work... I'll add my current loop – DoubleJ Aug 13 '18 at 19:55
  • Possible duplicate of [Better way to sum a property value in an array](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array) – Luca Kiebel Aug 13 '18 at 19:56
  • The problem with your code is that `total` is not initialized and has an initial value of `undefined`. In JavaScript, `undefined` plus a number is NaN (and NaN plus a number is NaN). Initialize the variable to zero and your loop should work. But as the answers below state, it's cleaner to use `.reduce()`. – TypeIA Aug 13 '18 at 20:12

4 Answers4

3

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.

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
  • wow, thank you, looks like it works now... What exactly is this "accumulator"? – DoubleJ Aug 13 '18 at 20:01
  • I've edited to hopefully provide a bit of clarity. The `accumulator` in this case is the total of all the items in the array. As we loop through the array, we add `item.price * item.amount` to the accumulator. The `, 0` at the very end tells the function to start our accumulator at `0`. – Tyler Roper Aug 13 '18 at 20:03
  • perfect, I think I understand now how this works, thank you very much! – DoubleJ Aug 13 '18 at 20:04
  • 1
    "*if you were trying to add every item in an array, you'd do `accummulator + currentItem`*" wouldn't you rather use `accummulator.push(currentItem)`? – Luca Kiebel Aug 13 '18 at 20:07
  • 1
    @Luca - It was a poor choice of words on my part. I didn't mean add every item **to** an array, but rather "add-up" the numbers within one. The obviously better way to explain this would have been *"if you were trying to sum the items of an array"*. I've edited to reflect this. – Tyler Roper Aug 13 '18 at 20:08
1

With Array.reduce():

const cartTotal = cart.reduce((total, item) => {
  return total + (Number(item.price) * Number(item.amount));
}, 0);
Jeremy M
  • 184
  • 5
1
  1. Iterate through the array
  2. Each iteration:
    • get the amount value, convert to integer
    • get the price value, convert to integer
    • Multiply these two
    • Add to a running total variable

When done, your running total variable has the total.

var total;
for (let i = 0; i < cart.length; i++) {
  total += parseInt(cart[i].price) * parseInt(cart[i].amount);
}
console.log(total);
BryanH
  • 5,826
  • 3
  • 34
  • 47
0

just iterate through it and calc

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

cart_list.forEach(function(obj){
    total_price+= obj.amount*obj.price;
});
console.log(total_price) //this is the total price
Atul
  • 420
  • 2
  • 10