10.28.2005 - sort() of a problem
Perhaps this is common knowledge, but I was unaware of it as were the two folks I mentioned it to who are both very solid coders:
The sort
method of the Array object in javascript will always sort lexicographically unless a comparison function is passed as an argument.
Meaning, an array with values of 0,5,9,10 will sort to 0,10,5,9 unless you write up a quick function like this:
function numericSort(a,b) {
return a-b;
}
...and pass that function as the argument to the sort method, a la sort(numericSort)
to get the sort you're expecting.
I wasted a bit of time fighting with what seemed a random issue until it dawned on me what was happening. Hopefully this will prevent anyone else from tripping over the same silly issue. See developer.mozilla.org for more info.
Comments have been closed for this post.