1

I am trying to loop through objects within an array, adding all values with the key 'price'.

var basket = [
    {
        price: "25.00",
        id: "Hat"
    }, {
        price: "50.00",
        id: "Jacket"
    }
]

/*objects within array. purpose = able to use a for loop using .length as follows*/

function test() {
    for(var i = 0; i < basket.length; i++){
        totalPrice = 0;
        alert(itemPrice);
        itemNum = basket[i];
        itemPrice = parseFloat(itemNum.price);
        totalPrice += itemPrice;
    }
    alert(totalPrice);
}

My itemPrice alert shows that the loop runs through both objects, flashing 25 then 50. Why is my totalPrice variable only storing the second price, 50? The operator += should be the same as totalPrice = totalPrice + itemPrice? Any explanation as well as fixes would be very much appreciated, trying to get a good understanding!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
DVCITIS
  • 1,067
  • 3
  • 16
  • 36
  • 4
    Because you set totalPrice to 0 in the loop. You should do it before the loop. – Diego Basch Jan 12 '13 at 03:28
  • 1
    Or you could just use [`Array.reduce()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce): `var totalPrice = basket.reduce(function(pr, cur) { return pr + parseFloat(cur.price); }, 0);` (demo: http://jsfiddle.net/XqU5P/) – NullUserException Jan 12 '13 at 03:40

2 Answers2

2

The first time you enter the loop, you set totalPrice to 0. Then you add the first item price, so totalPrice is 25. Then you enter the loop for the second time, set totalPrice to 0 again, 0 + 50 = 50.

You should initialize totalPrice before the loop.

Diego Basch
  • 12,764
  • 2
  • 29
  • 24
0

use reduce:

basket.reduce( function( previousValue, currentValue ){
           return previousValue += parseInt(currentValue.price) 
 }, 0);

example: http://jsfiddle.net/ysJS8/

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce

Chris DaMour
  • 3,650
  • 28
  • 37