I can’t take full credit for this since I found some version of this function out there somewhere, but since it’s not that easy to find I thought I’d repost it.
If you need to numerically sort multiple columns in a DataGrid without creating a separate method for each based on its dataField, then use this:
/**
* Numerically sorts a column in the DataGrid.
*
* @param fieldName The string name for the dataField in the column that you want to sort.
*/
private function numericSortByField(fieldName:String):Function
{
return function(obj1:Object, obj2:Object):int
{
var value1:Number = (obj1[fieldName] == '' || obj1[fieldName] == null) ? null : new Number(obj1[fieldName]);
var value2:Number = (obj2[fieldName] == '' || obj2[fieldName] == null) ? null : new Number(obj2[fieldName]);
return ObjectUtil.numericCompare(value1, value2);
}
}
By default, the DataGrid’s sort converts your data to strings so this ensures it’s really doing a numeric sort (and is a generic one at that).
Finish it off by making sure to set the sortCompareFunction for your columns like so:
myColumn.sortCompareFunction = this.numericSortByField("myDataField");
#1 by Rkannan - August 30th, 2010 at 12:07
Awesome… Saved a lot of time.
Thanks,
RKannan.
#2 by Karthik - October 29th, 2010 at 09:39
i had a generic sort fn…and a specific sortCompareFn for every numeric column, that was just getting the dataField out and calling the generic fn. But this tip made it even more generic and saved a few lines of code! thank you!
#3 by Brian Robert - April 26th, 2011 at 19:01
Hello, thanks for the awesome code. My dataprovider is an XML Collection, and my datafield is often like “stats.sensors” which didn’t work. So here’s my little modification (part of):
var fieldDepth:int = fieldName.split(”.”).length;
var fieldsNames:Array = fieldName.split(”.”);
var value1:Number = (obj1[fieldsNames[0]][fieldsNames[1]] == ” || obj1[fieldsNames[0]][fieldsNames[1]] == null) ? null : new Number(obj1[fieldsNames[0]][fieldsNames[1]]);
#4 by Rachel - June 25th, 2011 at 17:03
Thanks for posting the code, it worked brilliantly.
I called the function directly in my MXML file as so: