88

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?

3
  • You might want to check Compare two Arrays Javascript - Associative Commented Oct 26, 2010 at 16:52
  • 1
    i think some of the answers are going for "lines of code" efficiency, like larry k, while others are going for speed of execution efficiency. sadly, you didn't state which you were looking for :) Commented Oct 26, 2010 at 17:01
  • @koopajah Didn't vote to close as the difference is that the older question is set comparison and this is set comparison along with order of contents. So set a == b && a set is in the same order as b. Commented Feb 14, 2013 at 13:02

2 Answers 2

151

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;
}
Sign up to request clarification or add additional context in comments.

8 Comments

It's safest, fastest, more flexible, always accurate, and actually more "elegant" that the array.join() approach -- once the function is defined. It's also less memory intensive, if that becomes an issue.
Nice approach. There is a little issue: The variable i should go from arr1.length - 1 to 0, not from arr1.length to 0.
@mimarcel: The i-- statement evaluates once before the iteration starts.
@palswim you are right! i dind't realise the i-- has a double trick. :)
@AniruddhaDas: This will only work on "sorted" arrays because the question asked for equality in order, not just isomorphism.
|
48

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

7 Comments

This is plain wrong as it seem to suggest that [ 1, 2 ] equals [ '1,2' ] and also equals [ 1, '2' ]..... etc. etc.
It overlooked the type of each item.
Just ran some quick tests and a for loop is much, MUCH faster than the toString method. In my tests, the worst-case scenario for the for loop was being 20x faster. The worst case was the for loop being 80x faster. So basically don't ever use this method, it's both wrong and slow :).
Thanks, could be useful to quickly test 2 arrays and remain readable even if it's not THE perfect way to do it ;)
Or array1.join() == array3.join(); but this does not check for type
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.