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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: