How to check identical array in most efficient way?

ssdesign picture ssdesign · Oct 26, 2010 · Viewed 116.9k times · Source

I want to check if the two arrays are identical (not content wise, but in exact order).

For example:

 array1 = [1,2,3,4,5]
 array2 = [1,2,3,4,5]
 array3 = [3,5,1,2,4]

Array 1 and 2 are identical but 3 is not.

Is there a good way to do this in JavaScript?

Answer

palswim picture palswim · Oct 26, 2010

So, what's wrong with checking each element iteratively?

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;
}