开发者

Doubt in action script for Flex: getting unique elements from an ArrayCollection

开发者 https://www.devze.com 2022-12-23 04:55 出处:网络
I have an ArrayCollection as mentioned below. private var initDG:ArrayCollection = new ArrayCollection([

I have an ArrayCollection as mentioned below.

        private var initDG:ArrayCollection = new ArrayCollection([
            {fact: "Order #2314", appName: "AA"},

            {fact: "Order #2315", appName: "BB"}

            {fact: "Order #2316", appName: "BB"}
                            ...

            {fact: "Order #2320", appName: "CC"}

            {fact: "Order #2321", appName: "CC"}

            ]);

I want to populate a ComboBox with UNIQUE VALUES of "appName" field from the ArrayCol开发者_C百科lection initDG.

<mx:ComboBox id="appCombo" dataProvider="{initDG}" labelField="appName"/>

One method I could think is to loop through the Array objects and for each object check and push unique appName entries into another Array. Is there any better solution available?


That sounds good to me:

var unique:Object = {};
var value:String;
var array:Array = initDG.toArray();
var result:Array = [];
var i:int = 0;
var n:int = array.length;
for (i; i < n; i++)
{
 value = array[i].appName;
 if (!unique[value])
 {
  unique[value] = true;
  result.push(value);
 }

}
return new ArrayCollection(result);


You can used this class for finding unique arraycollection:

tempArray=_uniqueArray.applyUnqiueKey1(_normalsearchdata.toArray());

"uniqueArray" this is package name and _normalsearchdata is ArrayCollection;

package{
    import mx.collections.ArrayCollection;
    public class applyUniqueKey{
        private var tempArray:Array;

        private var tempIndex = 0;
        public var temp:String;
        public function applyUnqiueKey1(myArray)

        {
            tempArray = new Array();
            tempIndex = 0;  
            myArray.sort();
            tempArray[0] = myArray[0];
            tempIndex++;

            for(var i=1; i<myArray.length; i++) {
                if(myArray[i] != myArray[i-1]) {
                    tempArray[tempIndex] = myArray[i];
                    tempIndex++;
                }
            }
            var temp=String(tempArray.join());
            return new ArrayCollection(tempArray);
        }
    }
}


Alas, there is no unique() method in ActionScript's Array, but you can approximate it like this:

var names:Array = initDG.toArray().map(
    function (e:Object, i:Number, a:Array):String {
        return e.appName;
    }
);

var uniqueNames:Array = names.filter(
    function (name:String, i:Number, a:Array):Boolean {
                // Only returns true for the first instance.
        return names.indexOf(name) == i;
    }
);

Note this happens to work because you are filtering strings, which are compared by value. This wouldn't be effective if you needed to filter arbitrary objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号