3 Replies Latest reply on Apr 30, 2007 5:02 PM by Rothrock

# How to check for equivalence between arrays

This may be a basic question, but why does my attached example return false? I would think that if two arrays contain the exact same number of elements, and those elements were identical, that the below example would return true. Is this a good example of “There is something fundamental about variables that you are overlooking,” or something?

Any help is appreciated.
• ###### 1. Re: How to check for equivalence between arrays
If you look at the == operator, you will see this:

"Two such variables are equal if they refer to the same object, array, or
function. Two separate arrays are never considered equal, even if they have
the same number of elements."

So, you need to compare element by element...

>> var aTestA:Array = [1];
var aTestB:Array = [1];

If you do trace(aTestA[0] == aTestB[0]);
you will get true...

--
Dave -
http://www.blurredistinction.com

• ###### 2. Re: How to check for equivalence between arrays
Thanks for the speedy response. I promise to look closer at the documentation first next time.

Take care.
• ###### 3. Re: How to check for equivalence between arrays
Of course before you do an element by element test, just test the lengths. If they are not the same then you know for sure that the test will fail and that they aren't equal. Only if they have the same length do you have any hope of them being equal.

Also of course, depending upon your needs, these two might be equal:

array1=new Array(0,1,2,3);
array2=new Array(3,2,1,0);

So don't forget to sort them if that is going to be important to you.

And finally if you do something like

array1=new Array(3,2,1,0);
tempArray=array1;
tempArray.sort();

remember that array1 will now be sorted too. So if you want to make a duplicate of an array use Array.slice();

And yes this is all in the help files! They are good and if you make good on your promise you will benefit a great deal! :)