How to check if all variables are different?

Is it possible to check if all the variables are different from each other?

var a = 1, b = 2, c = 3, d = 4;

if(a != b && a != c && a != d && b != a && b != c && b != d && c != a && c != b && c != d && d != a && d != b && d != c){
  //All numbers are different
}

      

eg

if(a != b != c != d){

}

      

+3


source to share


7 replies


You can store them all in an object and check if the number of keys matches the number of variables used, for example

var dummy = {};
dummy[a] = true;
dummy[b] = true;
dummy[c] = true;
dummy[d] = true;
console.log(Object.keys(dummy).length === 4);

      



If the values ​​are different, then a new key will be created each time, and the number of keys will be equal to the number of variables used.

+4


source


As Denys Séguret commented, if you have the correct structure for your data, then it can be done in a more elegant way.

However, with what you have, you can still simplify as you can remove duplicate checks.

For example, you check that a! = B and then later that b! = A. These two checks are actually the same, only in a different order.



Removing all duplicates gives you ...

if(a != b && a != c && a != d && b != c && b != d && c != d)

      

It's a little easier, although you're still better off structuring your data.

+2


source


Another way to use arrays

var a =10, b = 20, c=30, d =40, e =50;
alert(isVariablesDifferent(a,b,c,d,e));

function isVariablesDifferent(){
    var params = Array.prototype.slice.call(arguments);
    for(var i = 0; i < params.length; i++){
        if(params.lastIndexOf(params[i]) !== i){
            return false;
        }
    }
    return true;
}

      

+1


source


Make the array a variable. Iterate everything from first to last element and compare or otherwise hardcoded as shown below.

var a = 1, b = 2, c = 3, d = 4; 

if(a != b && a != c && a != d && b != c && b != d && c != d)
alert('all the variables are unique');

      

Link to my example code in jsfiddle

http://jsfiddle.net/parthipans/fNPvf/15217/

0


source


Another solution is push

variables in an array:

var a = 1,
  b = 2,
  c = 3,
  d = 4;

var arr = [];
arr.push(a);
arr.push(b);
arr.push(c);
arr.push(d);
var sorted_arr = arr.sort(); // You can define the comparing function here. 
// JS by default uses a crappy string compare.
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
  if (sorted_arr[i + 1] == sorted_arr[i]) {
    results.push(sorted_arr[i]);
  }
}

alert(results);
      

Run codeHide result


0


source


I find it difficult to imagine a quality answer without context, but since ECMA-Script 5 there is a function Array.prototype.every

to check if all elements of an array match a boolean expression. That is, you can express the same problem as follows:

var a = 1, b = 2, c = 3, d = 4; 

if(
  [b, c, d].every(function(someVar) { return someVar != a; })
  && [a, c, d].every(function(someVar) { return someVar != b })
  && [a, b, d].every(function(someVar) { return someVar != c })
  && [a, b, c].every(function(someVar) { return someVar != d })
) {
  alert("all different!");
}
      

Run codeHide result


Or check how you can simplify the implementation of the function different(...)

before Array.prototype

(or you can implement it as a property of some custom object or as a normal procedural function ...).

Array.prototype.different = function() {
  var results = [];
  
  for(var i = 0; i < this.length; i++) {
     // This is to clone the array so we don't modify the source one
     var arrayCopy = [].concat(this);
    
     // This drops the variable value to check and returns it
     var varValueToCheck = arrayCopy.splice(i, 1);
    
     // Then we use every to check that every variable value doesn't
     // equal current variable value to compare
     results.push(arrayCopy.every(
       function(varValue) {
         return varValue != varValueToCheck;
       })
     );
  }
  
  // Once we've got all boolean results, we call every() on
  // boolean results array to check that all items are TRUE
  // (i.e. no variable equals to other ones!)
  return results.every(function(result) { return result; });
};

// This should avoid that other libs could re-define "different"
// function, and also it should avoid for..in or forEach issues
// finding unexpected functions, as this function will be hidden 
// when iterating Array.prototype
Object.defineProperty(Array.prototype, "different", {
  enumerable: false,
  configurable: false,
  writable: false
});

var a = 1, b = 2, c = 3, d = 4; 

// Simplified check! 
if([a, b, c, d].different()) {
   alert("also all different!!!");  
}
      

Run codeHide result


Now the problem might be that simplifying a statement if

like yours with something like my suggestion is overkill or not, but that will depend on your actual use.

0


source


I made a function to test this for you. This can be costly with large datasets.

Here is the fiddle: https://jsfiddle.net/Luqm8z7b/

function uniqueTest(ary){
 for(var i=ary.pop(); ary.length > 0;i=ary.pop()){
  for(var j = 0; j < ary.length; j++){
   if(i === j) return false;
  }
 }
 return true;
}

var a = 1, b = 2, c = 3, d = 4;
var list = [];
list.push(a, b, c, d);
console.log(uniqueTest(list));

      

0


source







All Articles