Understanding the array.filter() method

Hello everyone, I am having a bit of an issue understanding how to use the array.filter method. Whenever I have used it It has been on an array of numbers.
But now I am trying to use it on an array of objects.
the objects look like this

1:
desc: "description"
id: "Bronze commoners' axe"
image: "/itemphotos/bronzeage/axe.jpg"
price: 25
title: "Bronze commoners' axe"

And I am trying to use the filter method to sort through the array and take out anything with a matching id, and then set the state to that new array.

Removefromcart = (id, price) => {
    this.setState((state) => ({
      cart: this.state.cart.filter((value) => value !== id),

      // total: state.total - price
    }));
    console.log(this.state.cart);
  };

It seems no matter what I do here it never filters out the item. It has been a very long time since I have worked with array methods like this, so any help would be appreciated. Thank you.

Hello!

Well, you’re not using it correctly :sweat_smile:.

If each element of the array is an object, what do you think you’re doing here?

(value) => value !== id

Have you logged to the console the value to see what it is?

(value) => {
  console.log('Array item:', value);
  // Output: Array item: ? <- what will be printed
  return value !== id;
}

Try that and see if you can find the problem.

In case you don’t know, the console can be seen by pressing control + shift + i and clicking on the Console tab or by right clicking on any element of the page and then clicking on Inspect element, then click the Console tab.

If you give up, the solution is here:

cart: this.state.cart.filter((value) => value.id !== id)
1 Like

I couldn’t ask for better help, thank you!

1 Like