Javascript compare 3 values
Solution 1:
You could shorten that to
if(g === h && g === f && g !== null)
{
//do something
}
For an actual way to compare multiple values (regardless of their number)
(inspired by/ simplified @Rohan Prabhu answer)
function areEqual(){
var len = arguments.length;
for (var i = 1; i< len; i++){
if (arguments[i] === null || arguments[i] !== arguments[i-1])
return false;
}
return true;
}
and call this with
if( areEqual(a,b,c,d,e,f,g,h) )
{
//do something
}
Solution 2:
What about
(new Set([a,b,c])).size === 1
Solution 3:
Works for any number of items.
ES5
if ([f, g, h].every(function (v, i, a) {
return (
v === a[0] &&
v !== null
);
})) {
// Do something
}
ES2015
if ([f, g, h].every((v, i, a) =>
v === a[0] &&
v !== null
)) {
// Do something
}
Solution 4:
I suggest you write a function where you give an array with all the values you want to compare and then iterate through the array to compare the values which each other:
function compareAllValues(a) {
for (var i = 0; i < a.length; i++) {
if (a[i] === null) { return false }
for (var j = 0; j < i; j++) {
if (a[j] !== a[i]) { return false }
}
}
return true;
}
that should be it, I think :)
Solution 5:
Write a simple function:
var checkAllArguments = function() {
var len = arguments.length;
var obj;
if(len == 0) {
return true;
} else {
if(arguments[0] == null) {
return false;
} else {
obj = arguments[0];
}
}
for(var i=1; i<len; i++) {
if(arguments[i] == null) {
return false;
}
if(obj == arguments[i]) {
continue;
} else {
return false;
}
}
return true;
}
Now, to check multiple arguments, all you have to do is:
if(checkAllArguments(g, h, f)) {
// Do something
}