views:

73

answers:

5

Hi, 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?

+1  A: 
array1_matches_array2 = array1.join() === array2.join(); // true
array1_matches_array3 = array1.join() === array3.join(); // false

updated: default arg for join is ","

Larry K
Have to ensure that no element have the type string and contain a comma.
palswim
very nice and elegant :)
ssdesign
I have an element with string but so far it is still able to compare it correctly. Could this cause problem later?
ssdesign
@ssdesign - Depends on your situation. For example, these two would be equal even though they're obviously different: `[1,'2,3',4,5].join()==[1,2,3,4,5].join()`
patrick dw
@ssdesign: Yes. This is an example of "time bomb coding". Depending on the value(s) of the string(s), this code will break.
Brock Adams
what about [1,2,3,4,'text',5,6] and [1,2,'text',3,5,4,6]
ssdesign
@ssdesign - Those would be different. The result of `join()` is to create a string of the data (in this case separated with commas). So in that example you would end up with: `"1,2,3,4,text,5,6"` and `"1,2,text,3,5,4,6"`, whereas in my example above you end up with `"1,2,3,4,5"` for both.
patrick dw
thanks, then this works perfect for me :)
ssdesign
what happens to the rating of this question? I saw 3 votes up, now its showing me 2. Its a good answer...
ssdesign
+1  A: 

You might want to check Compare two Arrays Javascript - Associative

Saul
A: 

Sort the arrays and then compare them.

array1.sort() == array2.sort();
Jacob Nelson
This would always be false because they are 2 different arrays. You need to compare content.
patrick dw
Hmm, I think he wants to check order, so `.sort()` would lose that data for him.
palswim
-1: this answer is not correct. Arrays are references to the data. So comparing two array variables will always give false. The problem is to compare the data that the arrays point to, the elements of the arrays. Eg: [1,2] == [1,2]; ==>> false.
Larry K
A: 

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

Adam
+9  A: 

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;
}
palswim
+1 I think this would be safest.
patrick dw
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.
Brock Adams
nice one too...
ssdesign