I’ve come across an odd sorting situation.
I was sorting numbers using greater-than to compare the size of the numbers.
var nums = [18, 30, 25, 12, 10, 15, 16, 9, 60, 72, 100];
nums.sort(function (a, b) {
return a > b;
});
console.log(nums);
// [15, 18, 9, 12, 10, 16, 25, 30, 60, 72, 100]
That is not in numerical order.
It does sort correctly though when you subtract one number from another.
var nums = [18, 30, 25, 12, 10, 15, 16, 9, 60, 72, 100];
nums.sort(function (a, b) {
return a - b;
});
console.log(nums);
// [9, 10, 12, 15, 16, 18, 25, 30, 60, 72, 100]
Does anyone know why the greater-than sign fails to work when sorting numbers?
Actually, I think that I’ve worked out why. The greater-than sign only gives a result of true/false which is interpreted as 1/0 and misses out the all important negative result.
Let this be a lesson, sorting numbers is achieved by subtraction, not by checking if one is greater than the other.