While working for a mobile application using Appcelerator Titanium, I came across the need to sort the rows in a table view for a travel search app that I was making. Since this is something that is not directly available in Titanium, I decided to make my own sort routine that would sort the data using Javascript sort. Given an array containing the data in the table view, sorting it using the Javascript sort is not difficult. You just need to call sort on the array and optionally give the comparator that you would like to use to sort the data.
/**
* Function that sorts the data using myComparator.
*/
function sort(data) {
data.sort(myComparator);
}
/**
* Comparator that defines order based on myValue in objects.
* @returns 1, -1, 0 denoting value in thisObject is greater than, less than or equal to value in thatObject
*/
function myComparator(thisObject, thatObject) {
if (thisObject.myValue > thatObject.myValue) {
return 1;
} else if (thisObject.myValue < thatObject.myValue) {
return -1;
}
return 0;
}
Unfortunately, just sorting the data at runtime in Titanium doesn’t change the rows in the table view. So there’s just one more step you need to do to make it work.
var data = tableview.data[0].rows; // Gets the first section from tableview.
// If you have more than one sections, you // need to sort each individually
// or modify the sort function accordingly.
sort(data);
tableview.setData(data);