22

I'm trying to check if an item exists in my array data and if it does then prevent it from being added to the array.

The handleCheck function will return true if an items already exists in the array but I'm not sure how to then use this to prevent the item from being added to the array.

I have attempted to use it in the handlePush function this.handleCheck(item) == false ? it should check if it's false and if so then push, if it returns true it should say it exists but at the moment this is not working as it will push to the array even if the item exists and it will never console.log 'exists`

How can I change my handlePush function to use handleCheck and prevent an item that already exists in the array to be added again?

https://www.webpackbin.com/bins/-KpnhkEKCpjXU0XlNlVm

import React from 'react'
import styled from 'styled-components'
import update from 'immutability-helper'

const Wrap = styled.div`
  height: auto;
  background: papayawhip;
  width: 200px;
  margin-bottom:10px;
`

export default class Hello extends React.Component {
  constructor() {
    super()
    this.state = {
    data: []
    }

    this.handlePush = this.handlePush.bind(this)
    this.handleRemove = this.handleRemove.bind(this)
    this.handleCheck = this.handleCheck.bind(this)
  }

  handlePush(item) {

    this.handleCheck(item) == false ?
    this.setState({
    data: update(this.state.data, {
      $push: [
        item
      ]
    })
    })

   : 'console.log('exists')
  }

   handleRemove(index) {
    this.setState({
    data: update(this.state.data, {
      $splice: [
        [index,1]
      ]
    })
    })
  }

handleCheck(val) {
 return this.state.data.some(item => val === item.name);
}

  render() {
    return(
    <div>
        <button onClick={() => this.handlePush({name: 'item2'})}>push</button>
        <button onClick={() => this.handlePush({name: 'item3'})}>push item3</button>
        {this.state.data.length > 1 ? this.state.data.map(product => 
          <Wrap onClick={this.handleRemove}>{product.name}</Wrap>) : 'unable to map' } 
        {console.log(this.state.data)}
        {console.log(this.handleCheck('item2'))}
        {console.log(this.handleCheck('item3'))}
      </div>
    )

  }
}
3
  • if you don't specifically need to use an array you could create a hashmap using object properties which would ensure uniqueness
    – Cookie
    Jul 24, 2017 at 9:52
  • 1
    thanks I'll look into the possibility of using a hashmap Jul 24, 2017 at 10:01
  • i wasn't trying to answer the question just suggest an alternative to help you out, if you end up using this approach you should leave an answer to your own question with what you did :)
    – Cookie
    Jul 24, 2017 at 10:02

3 Answers 3

43

it should be:

handleCheck(val) {
    return this.state.data.some(item => val.name === item.name);
}

because val here is an Object not a String.

Check this out: https://www.webpackbin.com/bins/-Kpo0Rk6Z8ysenWttr7q

2
  • To clarify: the {console.log(this.handleCheck('item2'))} is passing a string, but the <button onClick={() => this.handlePush({name: 'item2'})}>push</button> is passing an object. Jul 24, 2017 at 10:01
  • 1
    thanks this works and thanks for clarifying @DaveSalomon I can see where I was going wrong Jul 24, 2017 at 10:03
37

While searching for Check value exists in an array in React, I was landed in this page and would like to give a solution (apart from this question) for others who think there is any special case to check for a value in an array using React.

You can rightly use the default JavaScript method too. There is nothing special when it comes to React.

var arr = ["steve", "bob", "john"];

console.log(arr.indexOf("bob") > -1); //true

Thank you.

3
  • 2
    Genius... absolutely genius. Simplicity at its best. I tried all manner of methods but this simple one-liner... dude, thanks! Sep 28, 2020 at 10:31
  • 1
    I tried using this in my react app to validate a form input. This works well in all cases except when I enter and then remove "bob" from my input field, the validation does not fail for the empty field. Using includes() on the array instance fixed the problem for me.
    – RogerThat
    Oct 5, 2020 at 2:46
  • Genius , this helped me great ! Nov 20, 2022 at 10:50
20

Use the includes() method on the array instance.

console.log(['red', 'green'].includes('red'))
console.log(['red', 'green'].includes('blue'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.