Javascript sort() Gotcha

Javascript pop quiz!

What is the result of this code?

var arr = [12, 3, 24]

You: [3, 12, 24]

Me: Wrong, You get an F! The correct answer is: [12, 24, 3].

You: WTF?

Me: Array.prototype.sort() uses lexical ordering by default. That is to say, it converts everything to string before comparing them. Thus, '12' comes before '24' comes before '3'.

You: So how do you make it sort numbers?

Me: You pass it a comparator function as an argument:

arr.sort(function(a, b){
  return a - b

You: That makes sense, I guess. But still...that is pretty messed up.

blog comments powered by Disqus