View Full Version : comparing arrays
ljonny18
09-26-2007, 11:05 AM
Hi,
I have 2 arrays that I want to compare:
var a1:Array = new Array(2,1,3,0);
var a2:Array = new Array(0,2,3);
I want to compare the values in the arrays, and all the values that exist in a1 and dont exist in a2 (in this case 1 and 4), I want to put into a new array (a3):
a3 = (1,4)
how can I do this in AS3???
Thanks,
Jon.
flexy
09-27-2007, 01:04 PM
I think you'd need to iterate through your arrays:
private function matchArrays( a1:Array, a2:Array ) :Array
{
var a3:Array = new Array();
var len1:int = a1.length;
for( var i:int = 0; i<len1; i++ )
{
var len2:int = a2.length;
for( var j:int = 0; j<len2; j++ )
{
if( a1[i] == a2[j] )
{
a3.push( a1[i] );
break;
}
}
}
return a3;
}
ljonny18
09-27-2007, 03:25 PM
that is what I tried and was having problems with :(
in your example a3 = 2,3,0, and I only need to return the values that are in the first array and not in the second array etc....
e.g.
a1:Array = new Array(2,1,3,0);
a2:Array = new Array(0,2,3);
so I need a2:Array = new Array(1); - as "1" is tha value that is in the first array but not in the second.
Thanks,
Jon.
flexy
09-27-2007, 03:37 PM
How about?
private function matchArrays( a1:Array, a2:Array ) :Array
{
var a3:Array = new Array();
var len1:int = a1.length;
var notFound:Boolean = false;
for( var i:int = 0; i<len1; i++ )
{
if( notFound )
{
a3.push( a1[i-1] )
notFound = false;
}
var len2:int = a2.length;
for( var j:int = 0; j<len2; j++ )
{
if( a1[i] == a2[j] )
{
notFound = false;
break;
}
else
{
notFound = true;
}
}
}
return a3;
}
Jim Freer
09-28-2007, 01:35 AM
private function aNotInB
( avArrayA :Array,
avArrayB :Array )
:Array
{
var lvArray:Array = [];
for each( var avObjectA:Object in avArrayA )
{
if( avArrayB.indexOf( avObjectA ) == - 1 )
lvArray.push( avObjectA );
} // for each
return lvArray;
} // aNotInB
http://freerpad.blogspot.com/
ljonny18
09-28-2007, 09:57 AM
thats great - thanks to both of you.
I used something similar to "Jim Freer's" example in the end
cheers guys,
Jon.
flexy
09-28-2007, 10:53 AM
Yeh Jim's for...each is a better way of doing it.
likhim
02-27-2009, 08:45 AM
May I know how to compare two arraycollection and return the result as arraycollection?
randygland
05-20-2009, 11:18 PM
it's nice to see the logic of the longer version though, I find it easier to follow, even if it's less clean. :)
likhim, I need to do the same.. and will probably end up doing it by stripping relevant data from the ArrayCollections I want to compare into new Arrays.. comparing those arrays with Jim's for each function, then reconstructing the ARrayCollections with the results.
I will post the code.
|
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.