Symmetri Developer Blog

January 7, 2009

Search ArrayCollection for a property on an Object

Flash/Flex, Algorithms - By Shourov Bhattacharya

A common scenario is to have an ArrayCollection of Objects and to want to find a particular Object using some sort of criteria. Now Actionscript does provide the ability to find an element within an ArrayCollection using the getItemIndex(element) method, but for that you need to provide the exact element you are looking for as an argument. There is no good way to find an element given a match on a property - kind of like a search rather than a lookup. An implementation of that as a utility function is very simple*, but I can’t think of a better way to do it:

// search an ArrayCollection for a property on an object
static public function getItemIndexByProperty(array:ArrayCollection, property:String, value:String):Number
{
   for (var i:Number = 0; i < array.length; i++)
   {
      var obj:Object = Object(array[i])
      if (obj[property] == value)
      return i;
   }
   return -1;
}

*Of course, this only works with String properties.

Get free blog up and running in minutes with Blogsome
Theme designed by Janis Joseph