Gary Haran.com


Comparing Javascript Arrays

Posted in Programming by gary.haran on the August 3rd, 2009

Here was a javascript question I saw through the twittersphere from a programmer friend of mine:

in JavaScript [2253] < [288] is TRUE (!) … any suggestion to sort an array of arrays?

I fired off an answer saying that he could use a comparison function:

my_array.sort(function(a,b){ return -1, 0 or 1 depending on need })

Then it dawned on me that there was an explanation for why the returned value of the original comparison was true rather than false.

>>> [2253] < [288]
true
>>> [2253] - [288]
1965
>>> 2253 < 288
false

Javascript converts the array to numerical values and then assesses wether that result is truth. Unfortunately when inside an array it converts only once and then sees wether the result is true. In Javascript any number is treated as true unless it is 0.

I guess for this my friend will have to write his own comparison function but at least we can understand how the types get switched around on us with this example.