-
Comparing 2 different arrays
Hello all,
I've searched everywhere and can't seem to find a clear explanation or basic example. How do you compare the elements of 2 arrays to see if there is a match? Is this even possible? All suggestions are welcome.
Thanks,
Tone
-
I found this. Is it the only/best solution?
function compareArrayToArray( arr1:Array, arr2:Array ):Boolean
{
for (var i:int = 0; i < arr1.length; i++)
{
if( arr2.indexOf( arr1[i] ) < 0 ) return false; //a -1 index is returned if arr2 doesn't contain arr1[i]
}
return true; //if the for loop never broke, then arr2 must contain everything from arr1, return true
}
Thanks,
Tone
-
Not only is that not the best solution, it is also broken.
That will test whether arr2 has everything in arr1, but not whether they're in the same order, or whether arr2 has extra stuff.
To do a shallow equality test on two arrays, just iterate over the length (which had better be the same between them) and test each element.
Code:
function compareArrayToArray(a1:Array, a2:Array):Boolean{
if (a1 == null){
return a2 == null;
}else if (a2 == null){
return false;
} else if (a1.length != a2.length){
return false;
} else { //finally, the meat
for (var i:int = 0; i < a1.length; i++){
if (a1[i] != a2[i]){
return false;
}
}
}
return true;
}
-
That function is perfect, however the lengths of the arrays are not the same.
-
If the lengths of the arrays are not equal, how could the arrays be equal?
-
Do you mean an intersection, i.e. elements in one array that appear in an another?
Actionscript Code:
// Returns an array containing the elements in b that exist in a function intersect(a:Array, b:Array):Array { var c:Array = [], e:*; for each (e in b) { if ( a.indexOf(e) > -1 ) { c.push(e) } } return c; }
-
Thanks all for your help!!
Actually the solution I found works perfectly in my situation.
@5tonsOfFlax - I never said that the two arrays were equal in length. However, the solution you provided works perfectly for arrays that are of equal lengths. This is very valuable as well.
@hoeru - You provided a great solution that returns an array of items that match from the two arrays.
All in all, this thread is highly helpful for anyone looking for array comaprison solutions. Thanks all once again!!
Tone
-
Originally Posted by toneDigital
All in all, this thread is highly helpful for anyone looking for array comaprison solutions.
It would be more helpful if you posted your solution too!!!
-
Code:
function compareArrayToArray( arr1:Array, arr2:Array ):Boolean{
for (var i:int = 0; i < arr1.length; i++){
if( arr2.indexOf( arr1[i] ) < 0 ) return false; //a -1 index is returned if arr2 doesn't contain arr1[i]
}
return true; //if the for loop never broke, then arr2 must contain everything from arr1, return true
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|