JavaScript Lesson 24: Sorting An Array

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone

<Previous Lesson> [Table of Contents] <Next Lesson>

24.1: Introduction to Array Sorting in JavaScript

When we deal with data, an especially massive amount of data, it is a common practice to sort the data in a kind of order so that they are easier managed, analyzed and look up. For example, the bank will sort customers’ names in alphabetical order so that they can send the financial statements according to this order at the end of each month. All computer programming language provide certain kind of sorting methods or functions, JavaScript is no exception.

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
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 complete code to sort the Mark array is shown below:

<head><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 );


</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.

<Previous Lesson> [Table of Contents] <Next Lesson>

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone