Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!