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:

JavaScript

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:

JavaScript

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