David Zagorsky
David Zagorsky

Reputation: 73

Why does filter returns the same array?

I need to remove an item using filter, but it returns the same array... Im new to react.. so pls keep that in mind with the answers :)

* method *

removeItemHandler = (id) => {
    if (this.state.selectedProducts.length <= 0){
      return
    }
      let carsSelected = this.state.selectedProducts.filter(item => {
        return item !== id})
        debugger;
        console.log(`item removed`, carsSelected);}

debugger (clicked 3 items)

  removeItemHandler = (id) => { ***id = {id: 2, name: "Bugatti", price: 3200000, description: "Extremely Fast", total: 0, …}
***
    if (this.state.selectedProducts.length <= 0){
      return
    }
      let carsSelected = this.state.selectedProducts.filter(item => ***{ carsSelected = (3) [{…}, {…}, {…}]***

        return item !== id}) ***id = {id: 2, name: "Bugatti", price: 3200000, description: "Extremely Fast", total: 0, …}***
        debugger;

console.log returns the same array

Upvotes: 0

Views: 211

Answers (2)

chandanchaudhary
chandanchaudhary

Reputation: 305

You need to compare the id of the item with the id you have passed to filter out.

let carsSelected = this.state.selectedProducts.filter(item => { return item.id !== id.id});

Upvotes: 0

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

You should filter by item.id instead of item

let carsSelected = this.state.selectedProducts.filter(item => item.id !== id.id)
//                                                                 ^^

Note that you are passing an object as id parameter. And you are comparing two objects. This is not easily done in JavaScript. Object equality is not how it seems. For example:

var firstObject = {
    id: 1,
    foo: "foo",
    bar: "bar"
};

var secondObject = {
    id: 1,
    foo: "foo",
    bar: "bar"
};


console.log(firstObject === secondObject); // with triple "="
// Output: false

console.log(firstObject == secondObject);  // with double "="
// Output: false

Even both objects have the same properties with same values, they are not same objects.

Instead of comparing whole objects, you can compare their unique identifiers

For further reading: Object comparison in JavaScript

Upvotes: 2

Related Questions