2

I originally had the following callback passed as a parameter to the javascript array sort() function:

function sortNumber(a,b) {
return a-b;
}

However this doesn't work when my array contains positive and negative decimal numbers (i.e. -107.578, 97.453 etc.) How would I modify this to sort properly?

2
  • This callback function will sort an array of decimal numbers in ascending numerical order. Did you want it to do something different? Commented Jun 2, 2010 at 19:50
  • Uh... this should work regardless. Commented Jun 2, 2010 at 19:52

2 Answers 2

14

I don't see any problems with that function. Here's my test code:

var nums = [10, 5, 40, 25, -3412,4212, -107.578, 97.453];

function sortNumber(a,b){
   return a - b;
}

alert( nums.sort(sortNumber) );

Can you show some more of your code? It might be a problem with the array.

Sign up to request clarification or add additional context in comments.

1 Comment

sorry my fault, careless error in my code. this does work fine.
0
nums.sort(function(a, b) {
           if (a < 0 && b < 0  || a > 0 && b > 0) {
              return a-b; 
            } else if (a < 0) {
              return -1; 
            } else if (b < 0) {
             return 1; 
            } 
           });

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.