views:

2583

answers:

4

I am using a Flex dataGrid, and need to sort some of my columns numerically.
Looking at the sortCompareFunction, it seems like i need to create a different function for each column that i want to sort, because my sort function has to know what field it is sorting on.

Is there any way that I can pass the field to be sorted on into the function? so that I only need one numeric sorting function.

+1  A: 

I did it using this function:

function fieldNumericSorter(field:String):Function {
    return function (obj1:Object, obj2:Object):int {
        return sign( int(obj1[field]) - int(obj2[field]) );
    }
}

and for each column that needed sorting set

colToBeSorted.sortCompareFunction = fieldNumericSorter("fieldname");
Alex
A: 

what does the sign() method do?

A: 

If you are using a DataGrid with an XML dataProvider, this worked for me (modified from Alex's answer):

private function xmlDataGridNumericSorter(field:String):Function 
{

    return function (obj1:Object, obj2:Object):int 
    {
        var num:Number = ((Number)(obj1.attribute(field)) - (Number)(obj2.attribute(field)));
        return (num > 0) ? 1 : ((num < 0) ? -1 : 0);
    }

}

and

dataGridColumn.sortCompareFunction = xmlDataGridNumericSorter(xmlAttribute.name().toString());

A very nice solution, considering how common a procedure this probably is..

Thanks Alex, hope this helps people further.

A: 

I did not use a numeric function to sort - instead did the following:

arrayCollObject.addItem({Col1: rowData[0], Col2: parseFloat(rowData[1])});

This seems to do the sorting correctly.

crazy horse