How to do custom sorting in Javascript on arrays
by Cory Rauch 2008-08-26 Category: JavaScript

In this article I will cover how to do custom sorting of both singular and multi-dimensional arrays in JavaScript.

JavaScript already contains a standard method for sorting arrays. You can accomplish this by simply calling the sort() method of your array object. This is excellent but sometimes there is a need to do more complicated sorting. To accomplish this, JavaScript allows you to pass a custom sort call back to the sort() method. This custom call back needs to take two parameters, (a, b). It also requires you to return either a negative number if a < b, zero if a == b, or a positive number if a > b. Below is example code to sort an array of numbers in reverse order.

var myArray = new Array(0,1,1,2,3,5,8,13);

function customSort (a, b) {
return (a - b) * -1;
}

myArray.sort(customSort);
document.write(myArray.toString());

The above code will output: 13,8,5,3,2,1,1,0

What if you want to sort a multidimensional array in JavaScript? To do this simply treat "a" and "b" parameters as a row of the array. Below is example code to arrange the multidimensional array of people in age order, from youngest to oldest.

var myMultiArray = [ {"Name": "Steve", "Age":41},
{"Name": "Joe", "Age":55},
{"Name": "Robert", "Age":34},
{"Name": "Alex", "Age":35}];

function customMultiSort(a, b) {
return (a['Age'] - b['Age']);
}

myMultiArray.sort(customMultiSort);
document.write(myMultiArray.toSource());

The above code will output: [{Name:"Robert", Age:34}, {Name:"Alex", Age:35}, {Name:"Steve", Age:41}, {Name:"Joe", Age:55}]

Other ImprovedSource Articles:
JavaScript bracket notation allows you to use strange variable names
How to detect if your in a frame via JavaScript
Free JavaScript Solitaire Game

Valid HTML 4.01 Transitional