Problems "moving" items from one array collection to another

I had a situation today where I needed to loop through one array collection, check a property, and potentially move the item to another array collection. This happens all the time with “slushbox” controls – controls that allow a user to move items from left to right, etc.

Well, in this process of moving the items, I had to remove the item(s) from the array collection and add them to another array collection.

I was using the following syntax:


for each (var item:Object in myFirstArrayCollection) {
var idx:int = 0;
if ( item.foo = 'bar') {
mySecondArrayCollection.addItem( item );
idx = myFirstArrayCollection.getItemIndex( item );
myFirstArrayCollection.removeItemAt( idx );
}
}

The problem with this approach is that by removing items from the arrayCollection, the indexes were changing while still inside my for each loop. Therefore, not all of the items were being moved. For example, let’s say I wanted to remove items with the indexes 99,100,101. When I removed 99 in the for loop, all the items shifted their indexes by -1, so that item 100 was skipped (because it was now 99 which has already been looped over) and 101 was deleted.

No problem, I handled this condition by creating a queue of items to remove, then processed them all after the for each loop. Like this:

public function moveItems() : void {

for each (var item:Object in myFirstArrayCollection) {
var removeQueue:ArrayCollection = new ArrayCollection();

if ( item.foo = 'bar') {
mySecondArrayCollection.addItem( item );
removeQueue.addItem( item );
}
removeItems( removeQueue );

}

public function removeItems( items:ArrayCollection ) : void {
for each (item:Object in items) {
idx = myFirstArrayCollection.getItemIndex( item );
myFirstArrayCollection.removeItemAt( idx );
}
}

*This code is psuedo-code - don't try to copy and paste, just use the concept.

By doing the above, the processing of removing items is handled after the loop. This works much better and solves the dilemma of changing indexes while looping over the array.

Advertisements

2 Responses to Problems "moving" items from one array collection to another

  1. Andrew,for each () loops work great when you are not adding/removing elements from the collection.When removing elements, you should iterate "backwards".for (var j:int=totalCount-1; j>=0; j–) {var item:* = collection[j];…}This works great and allows you to remove elements will still iterating.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: