user3718908x100
user3718908x100

Reputation: 8509

Client Side Cart: Adding two items with same description in array

Hello i am building a cart using local storage i have soo far been able to add and remove items in the cart now what i want to do now is this:

When a user adds an item that already exists in the cart array the quantity property alone is updated instead of adding another separate item to the cart array, is there an array function that does this already?

Upvotes: 0

Views: 47

Answers (1)

Anchor
Anchor

Reputation: 1371

Assuming that each cart item is an object, just update the property of the object if the user has already added it to the cart:

for (var i=0; i<cartItems.length; i++) {
  if (cartItems[i].name == addedItem.name) {
    cartItems[i].quantity += 1
  }
}

Upvotes: 1

Related Questions