07/01/2009

JavaScript: Sorting Complex Arrays

I wasn't aware that JavaScript text sorting was case sensitive (well on ie7 I've verified it is). So, Here is a simple example of sorting an Object Array taking into account case sensitivity.

for (var i in searchList) {
var indexOfTerm = WordStartsWith(searchList[i].Text, searchPhrase);
if (indexOfTerm > -1) {
results[results.length] = { Item: searchList[i],
IndexOf: indexOfTerm,
toString: function() { return this.Item.Text.toUpperCase(); }
};
}
}

results.sort();

By overloading the toString method we can convert our sort key to upper case and boom sorting works properly.

P.S.,
WordStartsWith is a method that returns the index of a search term in a text string.
searchList is a JSON structure with a bunch of data for use by a custom auto complete.

Each item in the results array is an object thus I've overridden the toString method to return an upper case copy of the text item for use in sorting (The JavaScript array calls toString to get sortable data).

Over and Out

No comments: