Sorting a two dimensional array in javascript

Sorting arrays in JavaScript is done via the method array.sort().

Passing in a function reference into array.sort()

As touched on already, array.sort() accepts an optional parameter in the form of a function reference (lets call it sortfunction). The format of this function looks like this:


function sortfunction(a, b){
   //Compare "a" and "b" in some fashion, and return -1, 0, or 1

When such a function is passed into array.sort(), the array elements are sorted based on the relationship between each pair of elements “a” and “b” and the function’s return value. The three possible return numbers are: <0 (less than 0), 0, or >0 (greater than 0):

Less than 0: Sort “a” to be a lower index than “b”
Zero: “a” and “b” should be considered equal, and no sorting performed.
Greater than 0: Sort “b” to be a lower index than “a”.

To sort an array numerically and ascending for example, the body of your function would look like this:

function sortfunction(a, b){
return (a - b) //causes an array to be sorted numerically and ascending

Sorting a two dimensional array in numerical order

To sort an array in numerical order, simply pass a custom sortfunction into array.sort() that returns the difference between “a” and “b”, the two parameters indirectly/automatically fed into the function:

<script type="text/javascript">
var aa =[["b",3],["a",4],["e",2],["d",1]];
aa.sort(function(x,y){return x[1]-y[1]}); // Array now becomes [["d",1],["e",2],["b",3],["a",4]]

This works the way it does because whenever “a” is less than “b”, a negative value is returned, which results in the smaller elements always appearing to the left of the larger ones, in other words, ascending.

Sort an array numerically but descending isn’t much different, and just requires reversing the two operands “a” and “b”:

<script type="text/javascript">
var aa =[["b",3],["a",4],["e",2],["d",1]];
aa.sort(function(x,y){return y[1]-x[1]}); // Array now becomes [["a",4],["b",3],["e",2],["d",1]]

Sorting a two dimensional array in alphabetical order

<script type="text/javascript">
var aa =[["b",3],["a",4],["e",2],["d",1]];

function alphabetical(a, b)
	var A = a[0];
	var B = b[0].toLowerCase(); 
	A = A.toLowerCase();
	B = B.toLowerCase();
	if (A < B) return -1;
	if (A > B) return 1;
	return 0;

Share this Post:
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

2 Responses to “Sorting a two dimensional array in javascript”

Trackbacks are disabled.

  • 这个很有深度啊

  • 在来看下 呵呵