Multiple Dimensional Sorting
JavaScript does not have a built in way to do 2D, 3D, nD sorting so we need to code our own. The code below will allow us to mutliple dimensional sort on as many columns as our heart desires.
The Code
Array.prototype.sortMulti = function(){
var argsLen = arguments.length;
var args = arguments;
function custSort(a,b){
for(var i=0;i<argsLen;i++){
var col = args[i];
var x = a[col];
var y = b[col];
if(x===y)continue;
return x > y;
}
return 0;
}
return this.sort(custSort);
}
The code above is pretty simple. It extends Array so we have a new method we can call. The arguments of the method is the column indexes that we want to sort. The custSort method loops through the indexes we apply and determines the sort order. It is very simple and straight forward to use.
Example Usage
myArray = [
[1,"b",1],
[2,"a",3],
[2,"b",1],
[1,"a",4],
[3,"a",3],
[3,"a",-1],
[3,"a",0],
[1,"d",1],
[4,"a",2],
[1,"c",5]
];
var newOrder1 = myArray.sortMulti(0);
var newOrder2 = myArray.sortMulti(0,1);
var newOrder3 = myArray.sortMulti(0,1,2);
var newOrder4 = myArray.sortMulti(2,1);
The examples above show different sort orders, newOrder one only sorts one column while newOrder3 sorts in regards to three columns. You should notice that the index starts at zero and not one!
Hope this helps!
Eric Pascarello
TrackBacks[0]
Comments[0]
Posted by pascarello on May 29, 2009 11:38:44 AM EST