check condition if match any of the following

Viewed 326

I am trying to check a condition using the logical or operator and seems like I am doing that wrong. It works of course if it is just 1, but when I add other values it seems to be incorrect as in below. How do I make this work to check if it's more than one. Does something go in quotes instead?

if (data.Items.find((item) => item.OrgUnit?.Id === (parseInt(match))).Role.Id === 110 || 120 || 130 || 140) {
  alert = "test"
}

3 Answers

You can't compare against multiple values like that. You could use Array#includes instead.

if([110 , 120 , 130 ,140].includes(data.Items.find((item) => item.OrgUnit?.Id === (parseInt(match))).Role.Id)){

}

Because the left side of the equation needs to be repeated for every instance of ||

let roleId = data.Items.find((item) => item.OrgUnit?.Id === (parseInt(match))).Role.Id
if(roleId === 110 || roleId === 120 || roleId === 130 || roleId === 140){
  alert="test"
}

This could also be written like this:

let roleId = data.Items.find((item) => item.OrgUnit?.Id === (parseInt(match))).Role.Id
if([110,120,130,140].includes(roleId)){
  alert="test"
}

in addition to iota's answer , the following part of the code could fail

data.Items.find((item) => item.OrgUnit?.Id === (parseInt(match))).Role.Id

because find could return undefined , so you need to add ? to the result of find method

const values = [110,120,130,140];
const roleId = data.Items.find((item) => item.OrgUnit?.Id === (parseInt(match)))?.Role.Id
if (values.includes(roleId)) {
  alert = "test"
}
Related