Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda