05
Aug
07

Sorting an ArrayCollection using the SortField and Sort classes

Sometimes in life you just need data to be sorted. Whether its a case insensitive sort (for names) or a numeric sort (for, uh, numbers), you just want things sorted in a particular order.

This example demonstrates how you can take a bunch of random numbers in an ArrayCollection and sort them numerically in ascending order.

Full code after the jump.

Download source (ZIP, 1K) | View MXML

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white" creationComplete="init()">

    <mx:Script>
        <![CDATA[
            import mx.collections.SortField;
            import mx.collections.Sort;
            import mx.collections.ArrayCollection;

            [Bindable]
            private var arrColl:ArrayCollection;

            /** This method gets called by the main mx:Application tag and initializes/populates the ArrayCollection object with a bunch of random numbers. */
            private function init():void {
                var i:int;

                /* Initialize and populate the ArrayCollection object. */
                arrColl = new ArrayCollection();
                for (i = 0; i < 20; i++) {
                    arrColl.addItem({data:getRandomNumber().toFixed(4)});
                }
            }

            /** This method returns a random floating-point number between 0 and 10000. */
            private function getRandomNumber():Number {
                return Math.random() * 10000;
            }

            /** This method gets called by the Button control's click handler and creates a new SortField and Sort object which are used to sort the ArrayCollection. */
            private function button_click():void {
                /* Create the SortField object for the "data" field in the ArrayCollection object, and make sure we do a numeric sort. */
                var dataSortField:SortField = new SortField();
                dataSortField.name = "data";
                dataSortField.numeric = true;

                /* Create the Sort object and add the SortField object created earlier to the array of fields to sort on. */
                var numericDataSort:Sort = new Sort();
                numericDataSort.fields = [dataSortField];

                /* Set the ArrayCollection object's sort property to our custom sort, and refresh the ArrayCollection. */
                arrColl.sort = numericDataSort;
                arrColl.refresh();
            }
        ]]>
    </mx:Script>

    <mx:List id="list" dataProvider="{arrColl}" textAlign="right" labelField="data" width="100" />

    <mx:Button id="button" label="sort items" click="button_click()" />

</mx:Application>

View source is enabled in the following example.


9 Responses to “Sorting an ArrayCollection using the SortField and Sort classes”


  1. 1 andrei Aug 14th, 2007 at 7:30 am

    Thanks for the tip. Really useful. It would be also useful to know that to sort descending you need to add “dataSortField.descending = true;”

    Have phun,
    Andrei

  2. 2 peter Oct 3rd, 2007 at 12:51 pm

    If an ArrayCollection contains a number of Foo objects and Foo has an attribute an instance of the class Bar and Bar has an attribute of fizz, can a SortField be used to sort Foo’s by the fizz attribute? I’ve tried doing new SortField(’bar.fizz’) but get a runtime error stating that bar.fizz isn’t a property of Foo — even though it is. Is there any way around this?

  3. 3 valentineday Nov 4th, 2007 at 6:06 pm

    There is great!

    Hey Peterd, if I want to sort by text what code should I replace for below?

    dataSortField.numeric = true;

    Thanks

  4. 4 peterd Nov 4th, 2007 at 8:34 pm

    valentineday,

    I haven’t tested it, but you could either try passing “false”, or perhaps just comment out/delete that line altogether.

    Also, if you want to do a non-case-sensitive text search, you may want to try setting the caseInsensitive property to true.

    Peter

  5. 5 bader Dec 12th, 2007 at 7:11 am

    Hi,
    I’m looking for the same answer for as Peter stated [is there a one..?];

    peter Oct 3rd, 2007 at 12:51 pm
    If an ArrayCollection contains a number of Foo objects and Foo has an attribute an instance of the class Bar and Bar has an attribute of fizz, can a SortField be used to sort Foo’s by the fizz attribute? I’ve tried doing new SortField(’bar.fizz’) but get a runtime error stating that bar.fizz isn’t a property of Foo — even though it is. Is there any way around this?

    thanks,
    -bader

  6. 6 Jason Jan 18th, 2008 at 12:33 am

    Hi,
    I to, am looking for a solution to the same problem as bader & peter
    (If an ArrayCollection contains a number of Foo objects and Foo has an attribute an instance of the class Bar and Bar has an attribute of fizz, can a SortField be used to sort Foo’s by the fizz attribute? I’ve tried doing new SortField(’bar.fizz’) but get a runtime error stating that bar.fizz isn’t a property of Foo — even though it is. Is there any way around this?)

    You see i needed to use a itemRenderer for each column in my datagrid meaning that i had to populate each column using the code “data.etc”, the problem comes into play when i want to sort a column that displays a child element of one of the objects in my arrayCollection, how do i go about doin this? Been battling for a day or two.
    thanks,
    jason

  7. 7 vivek Jul 18th, 2008 at 5:36 am

    Hi,

    Could you please give me an example to sort numeric data in XMLListCollection? Here is my sample XML

    <group name="Esthetique" value="2997" cost="0.52">
    <group name="xx" value="652" cost="0.47">
    <group name="xyt" value="652" cost="0.54">
    <group name="sss" value="652" cost="0.23">
    <group name="ffsdfsd" value="652" cost="0.82">
    

    Thanks,
    VIvke

  8. 8 peterd Jul 18th, 2008 at 3:05 pm

    vivek,

    Here’s an example of sorting XMLListCollection using MXML and ActionScript:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    
        <mx:Script>
            <![CDATA[
                import mx.collections.SortField;
                import mx.collections.Sort;
    
                private function sortByField(value:String,
                            isNumeric:Boolean = false,
                            isDescending:Boolean = false):Boolean {
                    var sortField:SortField = new SortField(value);
                    sortField.numeric = isNumeric;
                    sortField.descending = isDescending;
                    var sort:Sort = new Sort();
                    sort.fields = [sortField];
                    xmlListColl.sort = sort;
                    return xmlListColl.refresh();
                }
            ]]>
        </mx:Script>
    
        <mx:XMLListCollection id="xmlListColl">
            <mx:source>
                <mx:XMLList>
                    <group name="Esthetique" value="2997" cost="0.52" />
                    <group name="xx" value="652" cost="0.47" />
                    <group name="xyt" value="652" cost="0.54" />
                    <group name="sss" value="652" cost="0.23" />
                    <group name="ffsdfsd" value="652" cost="0.82" />
                </mx:XMLList>
            </mx:source>
            <mx:sort>
                <mx:Sort>
                    <mx:SortField name="@cost"
                            numeric="true"
                            descending="true" />
                </mx:Sort>
            </mx:sort>
        </mx:XMLListCollection>
    
        <mx:Panel>
            <mx:DataGrid dataProvider="{xmlListColl}" width="100%">
                <mx:columns>
                    <mx:DataGridColumn dataField="@name" />
                    <mx:DataGridColumn dataField="@cost" />
                    <mx:DataGridColumn dataField="@value" />
                </mx:columns>
            </mx:DataGrid>
            <mx:ControlBar>
                <mx:Button label="Sort by @name"
                        click="sortByField('@name')" />
                <mx:Button label="Sort by @cost"
                        click="sortByField('@cost', true, true);" />
                <mx:Button label="Sort by @value"
                        click="sortByField('@value', true, true);" />
            </mx:ControlBar>
        </mx:Panel>
    
    </mx:Application>
    

    Happy Flexing!

    Peter

  9. 9 peterd Jul 18th, 2008 at 5:39 pm

    For another example of sorting XMLListCollection, see “Sorting XML documents using an XMLListCollection”.

    Peter

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".