As generally known, sort() callback function is supposed to return -1, 0 or 1, depending on how its arguments compare. Despite this, I often see sort callbacks written in the following way:
someArray.sort(function(a, b) { return a > b })
Although this obviously doesn’t conform the specs, since the callback only returns 0 or 1, it still seems to produce correct results:
a = []
for(i = 0; i < 1000; i++)
a.push(Math.floor(Math.random() * 1000))
console.log(a.sort(function(a, b) { return a > b }))
Can anyone provide an example where the above callback function will cause an array to be sorted incorrectly? Array elements don’t have to be numbers.
It all depends on the specific browser’s sorting implementation, whether it uses the less-than comparison, and whether it autocasts sorting function’s return value to int.
This fails in IE9, but works in Chrome:
This works in IE9 and Chrome: