Well, it’s been a while since my last post. I couldn’t find any interesting subjects to write about. Anyway, today I’ll write about sorting arrays. I’ll start with sorting arrays numerically and alphabetically, to introduce you some basic techniques. After that I’ll show you how to sort a multidimensional array.

Array.sort()

You can use Array.sort() for basic numerical and alphabetical sorting. Here are some examples:

//sorting integers
[1,3,2,5,4].sort(); // => 1,2,3,4,5
//sorting floats
[1.2,1.1,1.5,2.6,0.21].sort(); // => 0.21, 1.1, 1.2, 1.5, 2.6
//sorting both integers and floats
[1.0,1,2,2.0,1.5,2.5].sort(); // => 1, 1, 1.5, 2, 2, 2.5

//sorting chars
['a','c','e','b','d'].sort(); // => a,b,c,d,e
//sorting strings
['aa','cz','bd','cc','bcc','bc'].sort(); // => aa,bc,bcc,bd,cc,cz
//sorting both strings and chars
['aa','az','b','cc','bc'].sort(); //=> aa,az,b,bc,cc

//sorting integers and strings
['a',1,'c',3,'e',2,'b','d'].sort(); // => 1,2,3,a,b,c,d,e

Array.sort(callbackFunc)

You can also define your own sorting function. This callback function must have two input arguments, and always returns -1 (all integers < 0), 0 or 1(all integers > 0).

  • if callbackFunc(a,b) is less than 0, place a before b.
  • if callbackFunc(a,b) returns 0, leave a and b unchanged in respect to eachother.
  • if callbackFunc(a,b) is greater than 0, place a after b.

A basic example for sorting an array of integers using a callback function:

function callbackFunc(a, b){
	return a - b;
}

[1,3,2,5,4].sort(callbackFunc); // => 1,2,3,4,5

The callback function really come in handy to sort arrays of objects. Let’s say we have an array of object with three properties: ‘firstname’, ‘lastname’ and ‘age’. Let’s say we want to sort the object on the lastname and on the firstname. This is a way we could sort those objects:

var objectArray = [
	{firstname: 'Marie', 	lastname: 'Doe', 	age: 28},
	{firstname: 'Will', 	lastname: 'Brown', 	age: 28},
	{firstname: 'James', 	lastname: 'White', 	age: 28},
	{firstname: 'John', 	lastname: 'Doe', 	age: 25},
	{firstname: 'Sarah', 	lastname: 'Doe', 	age: 25},
	{firstname: 'George', 	lastname: 'Williams', 	age: 25}
];

function callbackFunc(a,b){

	if(a.lastname == b.lastname){

		if(a.firstname == b.firstname){
			return 0;
		}

		return (a.firstname < b.firstname) ? -1 : 1;
	}

	return (a.lastname < b.lastname) ? -1 : 1;
}

objectArray.sort(callbackFunc);

/**
 * After sorting the objectArray will be like this:
 * [
 * 	{firstname: 'Will', 	lastname: 'Brown',	age: 28},
 * 	{firstname: 'John', 	lastname: 'Doe',	age: 25},
 * 	{firstname: 'Marie', 	lastname: 'Doe',	age: 28},
 * 	{firstname: 'Sarah', 	lastname: 'Doe',	age: 25},
 * 	{firstname: 'James', 	lastname: 'White',	age: 28},
 * 	{firstname: 'George', 	lastname: 'Williams',	age: 25}
 * ]
 */

If you want to know more about sorting with Array.sort(), check out the Core JavaScript 1.5 Reference:Global Objects:Array:sort.