Abdul
Abdul

Reputation: 1040

Compare Multiple variables in 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.

Upvotes: 6

Views: 3430

Answers (5)

Pat
Pat

Reputation: 1

To avoid a comparison between the same element and itself

if (values[i] === values[j]) { }

I think that it should be upgraded to

if ( (values[i] === values[j]) && (i != j) ) { }

but thanks for the script

Upvotes: 0

rlemon
rlemon

Reputation: 17666

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

Upvotes: 1

livibetter
livibetter

Reputation: 20450

while is enough. This will work on any length of array. But the a array will be modified, you may need to duplicate.

a = [1, 2, 3, 4];
while (a.length > 1)
  if (a.indexOf(a.pop()) != -1) {
    alert("Value is same, Please change the value");
    break;
  }

My previous answer (in revision), which using for, was little embarrassing.

Upvotes: 1

Brian Glaz
Brian Glaz

Reputation: 15676

You could write a function to check them for you, maybe something like this:

EDIT: Based on other answers, you could make it more efficient with a sort

function areTwoEqual() {
    var arg_list = [].slice.call(arguments).sort(
        function(a,b) { return a-b; }
    );
    var vals = {};
    for(var i = 0, len = arg_list.length; i < len; i++) {
        if(vals[arg_list[i]]) {
            return true;
        }
        vals[arg_list[i]] = '1';
    }
    return false;
}

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

if(areTwoEqual(a,b,c,d)) {
    alert('Two values are identical!');
} else {
    alert('all values are unique');
}​

JSFiddle: http://jsfiddle.net/thesouthstar86/j7LmZ/

Upvotes: 0

Waleed Khan
Waleed Khan

Reputation: 11467

This checks to see if any of the values are the same as any of the other values:

var values = [a, b, c, d, e, f /* ... */];

function shared_values(values) {
    for (var i = 0; i < values.length; i++) {
        for (var j = i; j < values.length; j++) {
            if (values[i] === values[j]) {
                return true;
            }
        }
    }
    return true;
}

if (shared_values(values)) {
    // Don't submit form or whatever
}

Upvotes: 0

Related Questions