Skip to main content
Known Participant
April 30, 2007
Answered

How to check for equivalence between arrays

  • April 30, 2007
  • 3 replies
  • 210 views
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.
This topic has been closed for replies.
Correct answer Newsgroup_User
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 -
Head Developer
http://www.blurredistinction.com
Adobe Community Expert
http://www.adobe.com/communities/experts/


3 replies

Inspiring
May 1, 2007
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! :)
Known Participant
April 30, 2007
Thanks for the speedy response. I promise to look closer at the documentation first next time.

Take care.
Newsgroup_UserCorrect answer
Inspiring
April 30, 2007
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 -
Head Developer
http://www.blurredistinction.com
Adobe Community Expert
http://www.adobe.com/communities/experts/