October 21, 2012

Compare two diff array with same size

Question by Pranali

I have a simple application in which I want compare two arrays.

function check() {
    var Array1 = value.length;
    var Array2 = selected_value.length;
    alert(Array1 + "," + Array2);
    for (var i = 0; i < Array1; i++) {
        for (var j = 0; j < Array2; j++) {
            if (value[i] == selected_value[j]) {
                alert("both div are same");
            }
        }
    }
}​

my arrays have 4 elements each but the if condition is not satisfied.

Answer by Starx

Here is function, with which you can compare two arrays

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

Source

You can check if array return false, like this

if(!arrayEqual(arr1,arr2)) {
   // false
}
...

Please fill the form - I will response as fast as I can!