Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you compare multiple variables to see if they all equal the same value in JS?

Working in Javascript, I am trying to see if 5 different variables all contain the same value at a given time. The value could be 1 of 6 things, but I need to see if they are all the same regardless of which value it is. I have tried this:

if (die1 == die2 & die1 == die3 & die1 == die4 & die1 == die5) {
    yahtzeeQualify == true;
}

and this:

if (die1 == die2 == die3 == die4 == die5) {
    yahtzeeQualify == true;
}

Are either of these valid? If so, there is probably an error in my code somewhere else...if not, I'd really appreciate some help. I also have these variables in an array called dieArray as follows:

var dieArray = [die1, die2, die3, die4, die5];

It would be cool to learn a way to do this via the array, but if that isn't logical then so be it. I'll keep trying to think of a way on my own, but up until now I've been stuck...

like image 358
Eric David Sartor Avatar asked Apr 18 '15 00:04

Eric David Sartor


2 Answers

Are either of these valid?

They are "valid" (as in this is executable code) but they don't perform the computation you want. You want to use a logical AND (&&) not a bitwise AND.

The second one is just wrong. You run into type coercion issues and end up comparing die1 to either true or false.

It would be cool to learn a way to do this via the array

You can use Array#every and compare whether each element is equal to the first one:

if (dieArray.every(function(v) { return v === dieArray[0]; }))
// arrow functions make this nicer:
// if (dieArray.every(v => v === dieArray[0]))
like image 187
Felix Kling Avatar answered Sep 30 '22 03:09

Felix Kling


Solution with the Array.reduce:

var values = [die1, die2, die3, die4, die5];

var yahtzeeQualify = values.reduce(function(memo, element) {
   return element === values[0];
});
like image 27
NenadP Avatar answered Sep 30 '22 05:09

NenadP