Archive for May 15, 2007

JavaScript Array sort Method

Posted in JavaScript, Software, Web, internet, programming on May 15, 2007 by Joey

The sort method can be used to sort the elements of a JavaScript array. By default, elements of an array are sorted in alphabetical order.

var aryTest = ['nash','boozer','duncan'];
document.write(aryTest.sort());

The preceding example sorts an array alphabetically.

To sort a JavaScript array by some order other than alphabetical, a comparison function is needed.

function SortNumbers(a,b)
{
return a-b;
}
var aryTest = [10,20,15,5];
document.write(aryTest.sort(SortNumbers));

The preceding example defines a function on which to base the sorting of the array and then executes the sort based on that comparison function. The comparison function needs to return:

A negative number if a is less than b.
A positive number if a is greater than b.
0 if a and b are equal.

To sort the array of numbers in a descending order, simply the reverse the math to b-a in the comparison function, as follows:

function SortNumbers(a,b)
{
return b-a;
}
var aryTest = [10,20,15,5];
document.write(aryTest.sort(SortNumbers));