Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
Array management in Javascript

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.
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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; }

about 4 years ago · Juan Pablo Isaza Relatório

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());

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda