Skip to content

Using filter to show all objects except the one I am clicking on

I am trying to setup a “remove from cart” button but I ran into some issues. I am having a hard time explaining what I mean, but I will do my best.

So pretty much, my goal is to filter out the product from the cart that the user is clicking on, I am doing this by targeting the ID. Every product has one. So I did this:

let id = e.currentTarget.getAttribute("itemid");

const clonedCartItems = JSON.parse(JSON.stringify(cartItems));


let newCart = clonedCartItems.filter(
  (ele, ind) => ind === clonedCartItems.findIndex((elem) => !== id)


But the issue I am having is that I currently have 3 items in the cart. But if I remove one, the other two should console log. But only one of them is logging, I am guessing I would need a loop somewhere? I am just unsure how I should tackle the problem.

If you need me to explain better, let me know and I will do my best!



Can you not just do:

let newCart = clonedCartItems.filter(
  (elem) => !== id

The filter method just requires a callback which needs to return a Boolean, if true the element should be kept or discarded otherwise.

You need to return !== id because this will be true for all items except for which the id ==

Doc referenced by @hellogoodnight