Jump to content

Can someone explain this sort function from w3 tutorial to me


music_lp90
 Share

Recommended Posts

Hi, I needed to sort some numbers using javascript, so I used the tutorial from W3, but I have no idea why this function works. Here's the code:

<html><body><script type="text/javascript">function sortNumber(a, {return a - b}var arr = new Array(6)arr[0] = "10"arr[1] = "5"arr[2] = "40"arr[3] = "25"arr[4] = "1000"arr[5] = "1"document.write(arr + "<br />")document.write(arr.sort(sortNumber))</script></body></html>

I'm confused by the function, how does a-b end up making the numbers sort properly?Thanks for your help!

Link to comment
Share on other sites

If a is less then b then the return value is negative, and it means that a comes before b. If a is greater then b then the return value is positive, and b needs to come before a. The reverse if you're sorting from high to low. If a and b are equal then the function returns 0 and it won't change the order of the two items being compared. The sort function runs through the array and for each pair of values it comes to, it passes them to the compare function as a and b. The sort function will swap the two elements if the return value is negative, sort backwards until the return value is positive or 0, and then move on to check the next pair. If you want it to sort from high to low then you can have the function return b - a.Also, you shouldn't put those numbers in quotes, it makes them strings.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...