Monday, 04 Aug 2008 18:55 EST
Sorting 2D Arrays in JavaScript
So you're working with a 2D array in JavaScript and you need to find a way to sort the damn thing. As it turns out, it's not nearly as bad as you might think. While JavaScript does not have a built in 2D array sort function to go along with array
.sort(), you are able to utilize good old
sort() by passing it a custom comparison function. Let start with the following 2D array:
var customers = new Array();
customers[0] = {lastName:"Williams", firstName:"Tom", company:"ABC Inc"};
customers[1] = {lastName:"Smith", firstName:"John", company:"123 Ltd"};
customers[2] = {lastName:"Johnson", firstName:"Bob", company:"Johnson Co"};
By default,
customers.sort() will sort on the first field defined in the array,
lastName. Let's say we want to sort on
company, though. All we need to do is create a custom comparison function which will grab the value of
company, compare the two and return 1 if
a.company is higher in the order and -1 if
b.company is higher. Very simple, yet very powerful.
function sortByCompany(a, b) {
var x = a.company;
var y = b.company;
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
Now you simply call JavaScript's standard array sort function with the name of your comparison function as the only parameter.
customers.sort(sortByCompany);
To sort descending, simply swap
1 and
-1 in the comparison function.
function sortByCompanyDESC(a, b) {
var x = a.company;
var y = b.company;
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}
customers.sort(sortByCompanyDESC);
As always, if you have a technique that you think is better or a tweak that improves on this code, please share it in the comments. If you have a tip, a trick or an idea for my next post, please don't hesitate to
contact me.
3 Comments So Far