eddie21leeds Posted January 23, 2009 Share Posted January 23, 2009 as before i am reading through the w3scools javascript tutorials. i dont get this one at all. it is an example of using the sort() method to numerically sort an array. <html> <body> <script type="text/javascript"> function sortNumber(a, b) { 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> the bit i dont get is how the sortNumber() function works... can anybody explain please?? thanks in advance! Quote Link to comment Share on other sites More sharing options...
TLawrence Posted January 23, 2009 Share Posted January 23, 2009 First of all, understand that the javascript sort() function sorts lexographically (alphabetically). That's why the sortNumber function was added...to sort the numbers numerically, not alphabetically. On to the function... The function returns the difference between 'a' and 'b', the two values passed. It works because whenever 'a' is less than 'b', a negative value is returned which results in the smaller elements always appearing to the left of the larger ones (ascending). When such a function is passed into array.sort(), the array elements are sorted based on the relationship between each pair of elements 'a' and 'b' and the function's return value. This exact function along with additional information about the sort() function is explained in greater detail at http://www.javascriptkit.com/javatutors/arraysort.shtml Quote Link to comment Share on other sites More sharing options...
eddie21leeds Posted January 23, 2009 Author Share Posted January 23, 2009 ok thanks. i think i get it now! Quote Link to comment Share on other sites More sharing options...
TLawrence Posted January 23, 2009 Share Posted January 23, 2009 If you're all set, be sure to mark this post "solved"! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.