A number sorting confusion

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.

4 Likes

a>b will return 1 or 0 (true or false).
a-b will return a positive number or a negative number or zero
The sort function needs three possibilites to work. This is provided by the a-b, but not by the a>b case.

You can use a>b if you take it a little further as follows.

 var nums = [18, 30, 25, 12, 10, 15, 16, 9, 60, 72, 100];
 nums.sort(function (a, b) {
    if(a < b){return -1}
    if(a > b){return 1}
    return 0;
});
console.log(nums);
// [9, 10, 12, 15, 16, 18, 25, 30, 60, 72, 100]
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.