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?

2
  • 1
    What data type is escalation? Commented Aug 10, 2010 at 14:46
  • It should be an int, but apparently it was being read in as a string. Makes since, since I get it from the XML as .text() Commented Aug 10, 2010 at 14:53

1 Answer 1

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;
 }
}
Sign up to request clarification or add additional context in comments.

3 Comments

You may want to add the radix parameter to parseInt as well: parseInt(a[0], 10) - this forces it to parse as base 10.
That fixed it! Thanks!! I'll mark it as answer as soon as it lets me
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. stackoverflow.com/questions/61088/hidden-features-of-javascript/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.