i found the following solution to add sorting capabilities to jQuery (ref: jQuery sort()). I’ve altered the solution to sort strings of unknown length. It works nicely, however as you might notice from the function name: it sorts acscending :-).
jQuery.fn.sort = function() {
return this.pushStack( [].sort.apply( this, arguments ), []);
};
function sortStringAscending(a,b){
var h1 = a.innerHTML;
var h2 = b.innerHTML;
var c = 0;
var str1 = null,
var str2 = null;
while(str1 == str2 && (c < h1.length && c < h2.length)) {
str1 = h1.substring(c,c+1).toLowerCase().charCodeAt(0);
str2 = h2.substring(c,c+1).toLowerCase().charCodeAt(0);
if(str1 > str2) {
r = 1;
} else if(str2 > str1) {
r = -1;
}
c += 1;
}
return r;
};
The function is used like this:
$('ol li').sort(sortStringAscending).appendTo('ol');
Is it possible to alter this code in such a way that the following will become possible?
$('ol li').sort(sortString, 0).appendTo('ol'); //0 for descending
$('ol li').sort(sortString, 1).appendTo('ol'); //1 for ascending
You are not going to be able to easily get an additional argument into the array sort function that the jQuery.fn.sort uses.
It will be easier to use two separate functions, one for ascending, and one for descending, but keep the actual comparision in a third function.
Also note that you can simply compare two strings, there is no need to compare them character by character, unless you want to have unpredictable sort order for items like “abc” and “abcd”.
Then you should be able to do