24.2 Sorting an Array
We have learned about arrays in previous lessons. In those lessons, we learned how to perform mathematical operations on data in an array and present them in a table. In this lesson, we will learn how to sort those data and present them in ascending order.
For example, we have a group of students who took computer programming test recently and obtain the marks as shown in the table below. Now, we can sort the mark in ascending order.
|Name of Student||Mark|
Sort is actually the method of an Array object. Therefore, we can initiate the sort method for the Mark using Mark.sort( compareValues ) where compareValues is the comparator function. This function is passed to the sort method as an argument.
The complete code to sort the Mark array is shown below:
The sorted mark show is 12 18 29 33 42 54 60 77 85 100 in ascending order.
Now click on Example 24.1 to view the actual output.