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

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

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