Reputation: 484
I have a cart[]
array like this:
[
{item_id: "0001", qty: "1"},
{item_id: "0002", qty: "2"},
{item_id: "0005", qty: "3"},
{item_id: "0001", qty: "5"}
]
I am trying to count all the qty
where item_id == 0001
for example. The problem is, the item_id
may be multiple times in the array; in this case twice. So I'm trying to add all the qty
up into a single value.
Here's what I have so far:
var this_item_qty = 0;
$.each(cart, function(index, value) {
if (value.item_id == "0001"){
this_item_qty = this_item_qty + value.qty;
}
console.log(this_item_qty);
// Returns 01 or 015...
});
But that doesn't seem to work. It's giving me values like 01
and 015
. It appears to be putting the values after another instead of calculating them together. What am I doing wrong?
Upvotes: 2
Views: 221
Reputation: 270
Use Number(value.qty)
var this_item_qty = 0;
$.each(cart, function(index, value) {
if (value.item_id == "0001"){
this_item_qty = this_item_qty + Number(value.qty);
}
console.log(this_item_qty);
});
Upvotes: 2
Reputation: 5550
It is taking the value.qty
as a string and concatenating it. You need:
this_item_qty = this_item_qty + parseInt(value.qty);
This will convert the string to an integer. If you want to be really robust you could check the parsed value for NaN
before adding it.
Upvotes: 1