user460920
user460920

Reputation: 887

Ascending number sorting - sort()

The call to n.sort(sortNo) doesn't specify any parameters for the function sortNo (which defines parameters of a and b). Can anyone explain why?

<script type="text/javascript">
 function sortNo(a,b)
 {
    return a - b;
 }
 var n = ["10", "5", "40", "25", "100", "1"];
 document.write(n.sort(sortNo));
</script>

Is return a - b; the formulae used?

I know that sortNo is provided with two items. Does a numerical operation return the following?

Upvotes: 2

Views: 3221

Answers (2)

Shadow
Shadow

Reputation: 6277

Both a and b are strings. So a-b makes no sense.

Use

     function sortNumber(a,b)
     {
        if (a < b)
           return 1;
       else if(a>b)
           return -1;
       return 0;
     }

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038910

This is because the Array.sort method expects a function pointer as argument. It will then loop through the array and invoke this function. You could also have used an anonymous function:

n.sort(function(a, b) {
    return a- b;
});

Upvotes: 4

Related Questions