I need some help, it's killing me. I have this array. that it's empty, when I click a button I want to add a product. but if the product is already in the array, I want to increase it's quantity in 1 on every click. but if the product is not inside the array, I want to add it.
here's the code.
addProduct(product) {
//check if array is empty, if it is, then set the product with quantity 1
if (this.cart.length === 0) {
product.quantity = 1;
this.cart.push(product);
} else {
//if array its not empty, check if the product is already in the array
for (let i = 0; i < this.cart.length; i++) {
if (this.cart[i].product_id == product.product_id) {
//if they're the same id, pop the product from the array
// and add it again but with quantity increased by one
this.cart.pop(product);
product.quantity += 1;
this.cart.push(product);
break;
} else {
//if product is not in the array, adds it with quantity 1
product.quantity = 1;
this.cart.push(product);
break;
}
}
}
Expected output:
1.- cart[{
product: "product_id": 1
quantity: 1
}]
---------clicked again-----------
2.- cart [{
product: "product_id" : 1
quantity: 2
}]
-----------clicked another product--------
3.- cart [{
product: "product_id" : 1
quantity: 2
product: "product_id": 2
quantity:1}]
actual output
1.- cart[{
product: "product_id": 1
quantity: 1
}]
---------clicked again-----------
2.- cart [{
product: "product_id" : 1
quantity: 2
}]
-----------clicked another product--------
3.- cart [{
product: "product_id" : 1
quantity: 2
product: "product_id": 2
quantity:1}]
-----------clicked another product--------
4.- cart [{
product: "product_id" : 1
quantity: 2
product: "product_id": 2
quantity:1
product: "product_id": 2
quantity:1}]
it repeats the second product on and on.
Array.popdoesn't take an argument, it removes the last element (see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…). Also, you don't need to remove and re-add the product at all because you're mutating it (which you also probably shouldn't do)elseis running on every iteration.