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

420
Visualizações
JavaScript: delete product from cart with minus button

I'm trying to eliminate the product added to the cart using the "-" button when the quantity reaches 1 unit. I hope someone can help me, I've been looking for a solution for two days. Thanks in advance.

//changeNumber

function changeNumber(action, id){

cart = cart.map((item)=> {

let = oldNumber = item.numberOfUnits;

if(item.id === id){

  if (action === "meno" && item.numberOfUnits >1) {
 oldNumber--
  } else if (action === "piu") {
    oldNumber++
     } 

     if (action === "meno" && item.numberOfUnits === 1){

       console.log("delete")
      console.log(cart.splice(item.id, 1));      
      }


updateCart();

}

return {
  ...item,
  numberOfUnits: oldNumber,
 
}

});


updateCart();
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The map function will not let you delete elements while it is looping.

There are two approches:

  1. Save the index of what you want to delete, and then after the .map(), call delete cart[index]
  2. Use a different technique to update the cart list (recommended)

Technique #1

function changeNumber(action, id) {
    var toRemove = null;
    var index = 0;

    [...]

    // Instead of the two console.logs
    toRemove = index;

    [...]

    // At the end of the map lambda
    index++;

    [...]

    // At the end of the changeNumber function
    if (toRemove !== null)
        delete cart[toRemove];
}

Technique #2

Instead of an array, use an object {id: item}. This allows you to access and modify a specific element without having to loop through everything.

var cart = {};

function addToCart(item) {
    if (item.id in cart) // Check if the item is already in the cart
        cart[item.id].numberOfUnits++;
    else {
        cart[item.id] = item; // You may want to copy the item instead of directly adding it
        item.numberOfUnits = 1; // May be unnecessary or unwanted, depending on your system
    }
}

function removeFromCart(item) {
    if (!(item.id in cart)) // If the item is already not in the cart
        return false; // The removal was already done
    cart[item.id].numberOfUnits--;
    if (cart[item.id].numberOfUnits <= 0) // The less-than is unnecessary, but a good check anyway
        delete cart[item.id];
    return true; // The removal was successful
}

// Example
addToCart({id: 5});
addToCart({id: 5});
addToCart({id: 7});

console.log(removeFromCart({id: 5})); // True; there was an item to remove
console.log(removeFromCart({id: 7})); // True; there was an item to remove
console.log(removeFromCart({id: 7})); // False; there was no item

console.log(cart);

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