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

130
Visualizações
Create array from State grouping IDs

I'm building a shopping cart, and my cart products array comes from a state. When I press the 'add to cart button, this function occurs(Infos is where the product Infos are):

const [cart, setCart] = useState([])
function addToCart() {
   setCart( arr => [...arr, {
     name: infos[id-2].fullName,
     value: infos[id-2].value,
     id: infos[id-2].id
}])}

And it's working fine, but I have repeating IDs on the cart array. This has implications on the checkout page and etc. So I need to create a new array from the cart with all the cart items, but excluding the repeated items, something like this:

const newCart = [{
   id: cart.id
   name: cart.name
   quantity: '' >times the id occurs on the cart array
   price: cart.value
   totalPrice: cart.value * quantity
}]

How can I do so? I'm using context to manage all my states

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Why put duplicate ids on the cart in first place, You can include one more field in the cart object and update that only.

const cart = [{ name: "A", value: 100, id: 1, quantity: 1 }];

function addToCart() {
  const item = infos[id - 2];
  setCart((arr) => {
    const newCart = [...arr];
    const existingItem = newCart.find((i) => i.id === item.id);
    if (existingItem) {
      existingItem.quantity++;
    } else {
      newCart.push({
        name: item.fullName,
        value: item.value,
        id: item.id,
        quantity: 1,
      });
    }
    return newCart;
  });
}
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