Friday, June 1, 2012

Removing items from array in Flex

In Flex when you are removing items from either an Array or an ArrayCollection they need to be removed in reverse order.  For example lets say that I have the following Array:

itemsArray = ["Item 1", "Item 2", "Item 3", "Item 2", "Item 4"]

If I want to remove all elements that match "Item 2" from the Array I would use the following code

for (var i:int = itemsArray.length - 1; i >= 0; i--)
{
if (itemsArray[i] === "Item 2")
{
itemsArray.splice(i, 1);
}
}

If you notice I am setting my i value to the length of the Array and then thus starting at the end of the Array ("Item 4") and working towards the front ("Item 1").

Once I run through the removal process the Array will look like this: 

    itemsArray = ["Item 1", "Item 3", "Item 4"]


Removing items from an ArrayCollection is almost identical with the exception of the removal process:

for (var i:int = itemsAC.length - 1; i >= 0; i--)
        {
if ( itemsAC [i].items ===  "Item 2")
itemsAC .removeItemAt(i);
}


Music: The Sugarcubes, The Smiths, The Cardigans 

No comments:

Post a Comment