Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Multiple variables in javascript

Tags:

javascript

I need to compare four variables.if any two variables are same i need show an alert. i did like the following way.

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

if((a==b)||(a==c)||(a==d)||(b==c)||(b==d)||(c==d)){
alert("Value is same, Please change the value");
return false;
}

Is that possible to reduce the expression to one condition instant of checking all the variables separately.Kindly advice ... TnQ in advance.

like image 647
Abdul Avatar asked Nov 27 '12 04:11

Abdul


1 Answers

well, i'll toss this into the ring, albeit it is likely not the right approach to this but it is fun. (note: browser compatibility issues and possibly over-kill is about to precede)

var a = 1,
    b = 2,
    c = 1,
    d = 3;
[a, b, c, d].sort(function(a, b) {
    return a - b;
}).reduce(function(a, b) {
    if (a == b) {
        alert('HERE');
    }
    return b;
});

demo here:
http://jsfiddle.net/rlemon/Eu4qG/

further readings:
Array.reduce
Array.sort

like image 193
rlemon Avatar answered Sep 20 '22 16:09

rlemon