0

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.
3
  • is the product object is: ``` { product: String, quantity: Number } ``` or ``` { product_id: String, quantity: Number } ``` or ``` { product: { product_id: String, }, quantity: Number } ``` your code is not clear without commas Commented May 27, 2022 at 19:51
  • Array.pop doesn'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) Commented May 27, 2022 at 19:54
  • Also, take a look at Array.find, you don't to loop over the array. Also also, your else is running on every iteration. Commented May 27, 2022 at 19:55

2 Answers 2

3

You could use find() to check if an object with the ID is already in the cart. If it is just add it, otherwise add up the quantities for the found product.

class Cart{
  constructor(){
    this.products = []
  }

  addProduct(product){
    const found = this.products.find(prod => prod.product_id === product.product_id)
    if(found === undefined){
      // product was not already in the cart
      this.products.push(product)
    }
    else {
      // product was already in the cart
      found.quantity += product.quantity
    }
  }

  show(){
    // show the contents of the cart
    console.log(JSON.stringify(this.products, null, 4))
  }
}

const cart = new Cart()

cart.addProduct({ product_id: 1, quantity: 1 })
cart.addProduct({ product_id: 2, quantity: 1 })
cart.addProduct({ product_id: 3, quantity: 1 })
cart.show()
cart.addProduct({ product_id: 1, quantity: 2 })
cart.show()
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

1 Comment

Using your logic but applied on my code and it worked. thanks a lot. Code updated: addProduct(product) { const found = this.cart.find( (prod) => prod.product_id === product.product_id ); if found === undefined) { producto.quantity = 1; this.cart.push(product); } else { found.quantity += 1; } },
0

Trying to keep as closely to your code as possible:

  1. Check to see if the products array is empty. If it is empty add in the product with a quantity of 1.
  2. If it isn't empty use findIndex to find the product.
  3. If it exists add one to its quantity.
  4. If it doesn't exist add it to the products array with a quantity of 1.

class Products {

  constructor() {
    this.products = [];
  }

  addProduct(product) {
    if (!this.products.length) {
      this.products.push({ ...product, quantity: 1 });
    } else {
      const index = this.products.findIndex(item => {
        return item.productId === product.productId;
      });
      if (index > -1) {
        ++this.products[index].quantity;
      } else {
        this.products.push({ ...product, quantity: 1 });
      }
    }
  }
  
  getProducts() {
    return this.products;
  }

}

const products = new Products();

products.addProduct({ productId: 1 });
products.addProduct({ productId: 3 });
products.addProduct({ productId: 2 });
products.addProduct({ productId: 3 });
products.addProduct({ productId: 2 });
console.log(products.getProducts());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.