actionscript-3apache-flexgroup-byarraycollectionflash-builder4.5

How can i create sql-like AS3 ArrayCollection grouping


I have an arrayCollection which I created dynamically like one at bottom:

arrCol = ({"ID":ids[i][0], "Price":ids[i][1], "OtherInfo":ids[i][2]});

I want to group data and summarise Price by ID.

If this ArrayCollection was a SQL table, I could use a query like this:

SELECT ID, SUM(Price), OtherInfo 
FROM TableA 
GROUP BY ID

So how can I set an AS3 function like the query example in SQL or is there any native ArrayCollection class for this?


Solution

  • Try this, there is no built in function available for your need(sum,groupby) so we need to do manually below code will help you.

    var arrCol:ArrayCollection = new ArrayCollection();
    
    arrCol.addItem({"ID":1, "Price":100, "OtherInfo":"info"});
    arrCol.addItem({"ID":1, "Price":700, "OtherInfo":"info"});
    arrCol.addItem({"ID":2, "Price":100, "OtherInfo":"info"});
    arrCol.addItem({"ID":2, "Price":200, "OtherInfo":"info"});
    arrCol.addItem({"ID":3, "Price":100, "OtherInfo":"info"});
    arrCol.addItem({"ID":3, "Price":400, "OtherInfo":"info"});
    arrCol.addItem({"ID":3, "Price":100, "OtherInfo":"info"});
    
    var dic:Dictionary = new Dictionary();
    
    for each (var item:Object in arrCol) 
    {
        if(!dic[item.ID]){
            dic[item.ID] = item;
        }
        else{                        
            var oldSumObj:Object = dic[item.ID];
            oldSumObj.Price +=item.Price;
            dic[item.ID] = oldSumObj;
        }
    }
    
    var groupedList:ArrayCollection = new ArrayCollection();
    
    for each (var itemObj:Object in dic) 
    {
        groupedList.addItem(itemObj);
    }   
    

    output will be:

    "groupedList"   mx.collections.ArrayCollection (@27af939)   
        [0] Object (@8836569)   
            ID  1   
            OtherInfo   "info"  
            Price   800 [0x320] 
        [1] Object (@87a7c71)   
            ID  2   
            OtherInfo   "info"  
            Price   300 [0x12c] 
        [2] Object (@87a7bc9)   
            ID  3   
            OtherInfo   "info"  
            Price   600 [0x258]