moo moo
moo moo

Reputation: 484

How do I count the total number of items in an array based on id and quantity?

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

Answers (3)

004123
004123

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

Peter Smith
Peter Smith

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

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

You need to use this_item_qty+= parseInt(value.qty)

Upvotes: 1

Related Questions