Benjamin Nadjar
Benjamin Nadjar

Reputation: 1

Compare each element of the array to state with react

Hi i dont't know how to compare each elements of the array to the state:

enter image description here

doesCustomerExist = () => {
  const { customers } = this.props;
  let result = customers.map(c => c.phone)
  if(result === this.state.phone)
    return (console.log('already exist'))
    console.log(result)
}

Upvotes: 0

Views: 2818

Answers (2)

Akrion
Akrion

Reputation: 18515

For this simply use Array.inlcudes:

const phone = "123";
const customers = ["111", "222", "333", "123"];

const isFound = customers.includes(phone)

console.log(isFound);

Upvotes: 1

remeus
remeus

Reputation: 2424

You can use indexOf to check if an array contains a given element.

For instance:

const phone = "123";
const customers = ["111", "222", "333", "123"];

const isInArray = customers.indexOf(phone) > -1;

console.log(isInArray);

Upvotes: 1

Related Questions