Arrays - Example 5

This example uses the sort() method built into an array to sort its contents, and displays the original array next to the sorted version.

The program uses the Math.random() function to generate random numbers. Unfortunately, these are decimal values, so we need the Math.floor() function to round them down to whole numbers.

Warning!

If one or more numbers in that array were less than 10, then they will not have been sorted into the correct order. Instead they will appear in the place that they would if all the numbers were reduced to only their first digit. This is because the function sort() only sorts items alphabetically, treating digits simply as characters in an extended alphabet.

Of course, if all the numbers are 10 or larger, then the problem won't occur, and you are probably wondering what all the fuss is about! Try clicking on "Refresh" or "Reload" a few times to see what I mean!

The next example, Example 5a, sorts the numbers without using sort(). Click here for Example 5a.


Go back
Go Back