Home > database >  how to remove single data among similar data, from array at a time?
how to remove single data among similar data, from array at a time?

Time:11-01

const deletItem=(id)=>{
        setCart(cart.filter(product=>product.id !== id))
        console.log(id);
    }

here when i want to delet single product all similar product id get deleted at a time ... how can I fix this .

CodePudding user response:

I think array splice is better used to delete an item from an array. Only you need to find the indexOf first.

var cart = [
  {name: 'product a', id: 1},
  {name: 'product b', id: 1},
  {name: 'product c', id: 2},
]  
const deleteItem = (id) => {
  var pos = cart.map(x => x.id).indexOf(id);
  if (pos >= 0) {
    cart.splice(pos, 1)
  }
}


deleteItem(1);
console.log(cart)

CodePudding user response:

Since you said it's deleting all similar product ids, it definitely sounds like your array has several items with the same id (which is supposed to be a unique, non-repeated identifier), and that's why you're filtering more than one.

  • Related