Skip to content
Advertisement

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

console.log(clonedCartItems);

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

console.log(newCart);

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!

Advertisement

Answer

Can you not just do:

let newCart = clonedCartItems.filter(
  (elem) => elem.id !== 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 elem.id !== id because this will be true for all items except for which the id == elem.id

Doc referenced by @hellogoodnight https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Advertisement