Check Variable Equality Against a List of Values

Check variable equality against a list of values

Using the answers provided, I ended up with the following:

Object.prototype.in = function() {
for(var i=0; i<arguments.length; i++)
if(arguments[i] == this) return true;
return false;
}

It can be called like:

if(foo.in(1, 3, 12)) {
// ...
}

Edit: I came across this 'trick' lately which is useful if the values are strings and do not contain special characters. For special characters is becomes ugly due to escaping and is also more error-prone due to that.

/foo|bar|something/.test(str);

To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:

/^(foo|bar|something)$/.test(str);

How to test multiple variables for equality against a single value?

You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:

if x == 1 or y == 1 or z == 1:

x and y are otherwise evaluated on their own (False if 0, True otherwise).

You can shorten that using a containment test against a tuple:

if 1 in (x, y, z):

or better still:

if 1 in {x, y, z}:

using a set to take advantage of the constant-cost membership test (i.e. in takes a fixed amount of time whatever the left-hand operand is).

Explanation

When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.

This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.

However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.

x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).

So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.

The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in {1, 2, 3}.

What's the prettiest way to compare one value against multiple values?

Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.

if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}

JavaScript: Simple way to check if variable is equal to one of two or more values?

You can stash your values inside an array and check whether the variable exists in the array by using [].indexOf:

if([5, 6].indexOf(x) > -1) {
// ...
}

If -1 is returned then the variable doesn't exist in the array.

How to check if a variable equals one of two values if a clean manner in JS

You could do:

if ([1, 2].includes(x)) {
// ....
}

Or:

if ([1, 2].indexOf(x) > -1) {
// ....
}

Or:

switch (x) {
case 1:
case 2:
// ....
break;
default:
}

I don't think they're "lighter" than your solution though.

Concise way to compare a variable against multiple values

You can use in operator:

for i in range(10):
if i in (3, 5) or math.sqrt(i) in (3, 5):
numbers.append(i)

or in case you expect each of the calculations to be in the same group of results, you can use any()

results = [1, 2, ..., too long list for single line]
expected = (3, 5)

if any([result in expected for result in results]):
print("Found!")

Just a minor nitpick, sqrt will most likely return a float sooner or later and this approach will be silly in the future, therefore math.isclose() or others will help you not to encounter float "bugs" such as:

2.99999999999999 in (3, 5)  # False

which will cause your condition to fail.

Concise way to compare against multiple values

With a regex:

if (/^(something|nothing|anything|everything)$/.exec('jesus')) alert('Who cares?');​

Or the opposite:

/^(something|nothing|anything|everything)$/.exec('jesus')||alert('Who cares?');​

[Update] Even shorter ;-)

if (/^(some|no|any|every)thing$/.exec('jesus')) alert('Who cares?');​

Compare multiple values against the same variable

Use indexOf with array of values

var valArr = ["kivi","apples","lychee","banana.C","mangos"];

if(valArr.indexOf(val) > -1){
.......
}

Best way to compare variable to multiple integers in javascript

You can use an array and then validate that id using the function includes.

const id = 2;

const array = [1, 2, 3];

if (array.includes(id)) console.log("I'm in!");


Related Topics



Leave a reply



Submit