-1

I have a React function, where I want to add an object to a javascript array. So far I have this

 selectAnimalHandler = (animal) =>{
    console.log(animal.id)
    if(this.state.animals.find(ani => ani !== animal )){
    this.setState(prevState =>(
        {selectedAnimals: [...prevState.selectedAnimals, animal]}))
    }
}

the logic is to check rather an element already exist in an array, and if it does not exist add it to the array. I try to make a condition, rather the element exists in the array or not. if it does not exist, nothing happens

Kristoffer Tølbøll
  • 3,157
  • 5
  • 34
  • 69
  • Possible duplicate of [How to determine if object is in array](https://stackoverflow.com/questions/4587061/how-to-determine-if-object-is-in-array) – Terry Jan 08 '19 at 21:44

1 Answers1

2

This statement this.state.animals.find(ani => ani !== animal ) returns a value even if animal is in the array.

You should use something like this !this.state.animals.find(ani => ani === animal )

Also, keep in mind that === or even == used on objects is only true if you compare two references to the same thing.

Titus
  • 22,031
  • 1
  • 23
  • 33