Checking if a value is different from any in a given list of values

180 Views Asked by At

I'm trying to improve an old React web application for work when i stumble upon this variable:

const condition = (
  param !== const1 && param !== const2 && param !== const3 && ...
)

Is there a best practise to improve this very long and condition?

3

There are 3 best solutions below

0
Some random IT boy On BEST ANSWER

The idiomatic way of performing such check if you're checking running the !== comparison for all items you should use the Array.every functional predicate.

It checks that every item matches the condition:

const condition = [value1, value2, value3].every(value => value !== parameter)
0
André On

You can shorten with the array method includes. This will return true if the array has the variable param, then use ! to switch the boolean to false:

const condition = ![const1, const2, const3, const4].includes(param);

Depending on your situation using condition with the ! operator (!condition) and declaring without might improve readability:

const condition = [const1, const2, const3, const4].includes(param);

The declaration above will likelly be my prefered option. However, there are a lot of other ways to achieve this:

In the line below indexOf will return -1 when param is not part of the array:

const condition = [const1, const2, const3, const4].indexOf(param) === -1;

In the line below array method every tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value:

const condition = [const1, const2, const3, const4].every(value => value !== param)
0
Whitespacecode On

Create an array for your conditions.

const conditions = [cond1, cond2, cond3, cond4];
return !condition.includes(conditions)

You can also use some

const conditions = [cond1, cond2, cond3, cond4];
return conditions.some(item => item !== condition)