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:
var Mark = [ 100, 12, 29, 42, 18, 33, 77, 54, 60, 85 ];
document.writeln( “<h1>Sorting an Array</h1>” );
ShowArray( “Marks in original order: “, Mark );
Mark.sort( compareValues ); // sort the array
ShowArray( “Marks in ascending order: “, Mark );
function ShowArray( Title, myArray )
document.writeln( “<p>” + Title +
myArray.join( ” ” ) + “</p>” );
function compareValues( value1, value2 )
return parseInt( value1 ) – parseInt( value2 );
</head><body onload = “SortData()”></body>
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.