What's the easiest / best way to get an array of values from a collection of arrays?
I have a collection of arrays with any number of objects. I know that every object has a given property. Is there a simple (aka "built-in") way to get an array of all values for this property in a collection?
For example, 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 an array "1,2,3,4 ....". Right now, I need to loop through the collection and push each value to the array. Since my collection can get large, I want to avoid the loop.
var myArray:Array /* of int */ = [];
for each (var item:Object in myArrayCollection)
{
myArray.push(item.id);
}
Does anyone have any suggestions?
Thank.
source to share
Once you get the base object Array
from ArrayCollection
using the property source
, you can use map
on 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;
}
source to share
According to the docs, ArrayCollection does not keep keys separate from values. They are stored as objects in the underlying array. I don't think there is any way to avoid iterating over them to extract only the keys, since you have to look at every object in the underlying array.
source to share