I have 3 values that I want to compare f, g and h. I have some code to check that they all equal each other and that none of them are null. I\'ve had a look online but could
Add a distinct
function to Array.prototype
:
Array.prototype.distinct = function() {
var result = [];
for(var i = 0; i < this.length; i++) {
if (result.indexOf(this[i]) == -1) {
result.push(this[i]);
}
}
return result;
}
Then do:
var myArray = [f, g, h];
if (myArray.indexOf(null) == -1 && myArray.unique().length == 1)
{
// no nulls and all elements have the same value!
}
Create an array of string and check the existance of next value in there
compareAnswers(a1: string, a2: string, a3: string): boolean {
this.compareAnswerArr.push(a1);
if (this.compareAnswerArr.includes(a2) == false) {
this.compareAnswerArr.push(a2);
if (this.compareAnswerArr.includes(a3) == false) {
return true;
} else return false;
}
else return false;}
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
}
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 :)
Works for any number of items.
if ([f, g, h].every(function (v, i, a) {
return (
v === a[0] &&
v !== null
);
})) {
// Do something
}
if ([f, g, h].every((v, i, a) =>
v === a[0] &&
v !== null
)) {
// Do something
}
What about
(new Set([a,b,c])).size === 1