Jump to content

[SOLVED] another beginner question!


eddie21leeds

Recommended Posts

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!

Link to comment
Share on other sites

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

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.