views:

64

answers:

1

Hi guys, I have a column in a data grid that has the values of "Monday", "Tuesday" etc, as varchars, and I wanted to know, how do i sort the column to be in the correct order. Doing a normal sort doesnt work obviously, as the days are not alphabetically ordered naturally (Wed after Thurs). I am assuming some sort of itemrenderer, but anyone got a snippet of code to illustrate how this would work?

Thanks

+1  A: 

As far as I know there is nothing built-in either to sort days of the week or get a day number from a day of the week, so you need to build both. You don't need a custom itemRenderer to do sorting though, just a sort compare function.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;

            [Bindable]
            private var days:ArrayCollection = 
                                new ArrayCollection([{day: "Wednesday"},
                                                    {day: "Thursday"},
                                                    {day: "Monday"},
                                                    {day: "Tuesday"},
                                                    {day: "Sunday"},
                                                    {day: "Saturday"},
                                                    {day: "Friday"}
                                                    ]);

            private static var dayMap:Object = {
                                            Sunday: 0,
                                            Monday: 1,
                                            Tuesday: 2,
                                            Wednesday: 3,
                                            Thursday: 4,
                                            Friday: 5,
                                            Saturday: 6};

            private function daySorter(day1:Object, day2:Object):int {
                var i1:int = dayMap[day1.day];
                var i2:int = dayMap[day2.day];

                return i1 < i2 ? -1 : i1 == i2 ? 0 : 1;
            }
        ]]>
    </mx:Script>

    <mx:DataGrid dataProvider="{days}">
        <mx:columns>
            <mx:DataGridColumn dataField="day" sortCompareFunction="{daySorter}" />
        </mx:columns>
    </mx:DataGrid>
</mx:Application>
Sam