3

I need to sort an array containing arrays in ascending numerical order. The data structure looks like this

array = [[escalation],//integer
         [name],
         [email],
         [blackberry]];

I try to sort the array using this function (sorting by escalation)

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

But my output still looks incorrect...

0 0 10 12 14 16 18 20 20 8

Any advice on how to fix this?

Mark Cheek
  • 265
  • 2
  • 10
  • 20

1 Answers1

1

From the sort output you provided, it looks like JavaScript is reading the array elements as strings. See if parseInt works:

function sortfcn(a,b){
 if(parseInt(a[0])<parseInt(b[0])){
    return -1;
 }
 else if(parseInt(a[0])>parseInt(b[0])){
    return 1;
 }
 else{
    return 0;
 }
}
Jeff
  • 21,744
  • 6
  • 51
  • 55
  • You may want to add the radix parameter to parseInt as well: `parseInt(a[0], 10)` - this forces it to parse as base 10. – Ryan Kinal Aug 10 '10 at 14:47
  • 1
    That fixed it! Thanks!! I'll mark it as answer as soon as it lets me – Mark Cheek Aug 10 '10 at 14:48
  • 1
    Unary `+` is handy here too. e.g. `if (+a[0] < +b[0])`. Neater than *parseInt*, IMO, and doesn't have the issue with the radix. http://stackoverflow.com/questions/61088/hidden-features-of-javascript/2243631#2243631 – Andy E Aug 10 '10 at 14:50