views:

269

answers:

2

I have an Array Collection with any number of Objects. I know each Object has a given property. Is there an easy (aka "built-in") way to get an Array of all the values of that property in the Collection?

For instance, let's say I have the following Collection:

var myArrayCollection:ArrayCollection = new ArrayCollection(
    {id: 1, name: "a"}
    {id: 2, name: "b"}
    {id: 3, name: "c"}
    {id: 4, name: "d"}
    ....
);

I want to get the Array "1,2,3,4....". Right now, I have to loop through the Collection and push each value to an Array. Since my Collection can get large, I want to avoid looping.

var myArray:Array /* of int */ = [];

for each (var item:Object in myArrayCollection)
{
    myArray.push(item.id);
}

Does anyone have any suggestions?

Thanks.

+2  A: 

According to the docs the ArrayCollection does not keep the keys separate from the values. They are stored as objects in an underlying array. I don't think there is any way to avoid looping over them to extract just the keys since you need to look at every object in the underlying array.

tvanfosson
While it's true that each object must be examined, an explicit loop is not necessary. The Array class offers convenience methods to help situations like this.
Matt Dillard
The loop just has a different author. Still it's best to use the framework provided mechanism absent some other reason.
tvanfosson
+2  A: 

Once you get the underlying Array object from the ArrayCollection using the source property, you can make use of the map method on the Array.

Your code will look something like this:

private function getElementIdArray():Array
{
    var arr:Array = myArrayCollection.source;
    var ids:Array = arr.map(getElementId);
    return ids;
}

private function getElementId(element:*, index:int, arr:Array):int 
{
    return element.id;
}
Matt Dillard
This is exactly what I was looking for.Thank you so much!
Eric Belair
This doesn't avoid looping, just avoids you writing the loop.
tvanfosson