AJT
AJT

Reputation: 266

React - Check if a value already exists in an array?

I'm working on a simple React shopping list where you can add/remove items from a list (pen here). It's working great so far except if you add a duplicate entry to the list and try and delete it, it gets confused (it's using the value as the key, so presumably that's why). To get around this I'd like to check if the value already exists in the list array when you add an item, and prevent it from being added. I've tried adding another check in the handleAddNew function by changing this: if (this.state.newItem.length > 0){ to this: if (this.state.newItem.length > 0 && this.state.items.includes(this.state.newItem) == false){ (line 18), but that doesn't seem to be working. Any ideas on how I should go about doing this?

Upvotes: 2

Views: 13455

Answers (1)

Matt Way
Matt Way

Reputation: 33151

The problem is that the entry form doesn't have access to the list to do any comparison. You can achieve your original thought by altering the addItem function to:

addItem(item) {
  // only add if the item doesn't exist in the list
  if(this.state.items.indexOf(item) < 0){
    this.setState((state) => ({
      items: state.items.concat([item])
    }))
  }
}

Note that I use indexOf here, but includes is also fine. You can do the comparison however you like.

Upvotes: 7

Related Questions