JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Lesson 24: Sorting Array


24.1 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 24.1. Now, we can sort the mark in ascending order.

Table 24.1
Name of Student Mark
Alex 100
Brian 12
Carmen 29
Dave 42
Graham 18
Keynes 33
Morgan 77
Olson 54
Selina 60
Terrence 85

Sorting data in an array in JavaScript required the use of the built-in method sort. The sort method examines its argument in the form of a function which is usually known as the comparator function. The comparator function compares two arguments and returns a positive value if the first argument is greater than the second argument, returns a zero value if the arguments are equal and returns a negative value if the first argument is less than the second argument.

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 JavaScript to sort the Mark array is as follows:

<script type = "text/javascript">
<!--
function SortData()
{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 );
}

</script>

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.


❮ Previous Lesson Next Lesson ❯


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy