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
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

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