Posts Tagged ‘method’

Sorted

Tuesday, February 9th, 2010

One of the problems I had to solve when writing my new jQuery listSplitter plugin was sorting an array of arrays/multidimensional array by one given column, eg

testArray = [[a, b], [b, a]];

How would you sort by the second column of the array?

I’m not sure if mine is the best solution, but here it is (it also works for an array of objects as well as an array of arrays):

/**
* sorts an array of arrays or objects using a specified column/property
*
* @param column (str/int) - the name/index of the column to use for sorting
* @param sortFunction (func) - the sort function to use for sorting (sort functions
*                             that can be used by array.sort() will also work here)
* @return array
*/
Array.prototype.sortByColumn = function(column, sortFunction) {
  return this.sort(function(a,b) {
    var testArray = [a[column], b[column]];
    testArray = (sortFunction) ? testArray.sort(sortFunction) : testArray.sort();
    return (testArray[0] == a[column]) ? -1 : 1;
  });
}

And to apply it to an array use it similarly to the array.sort() method, eg

myArray.sortByColumn(5);//sort alphabetically by column 5 of the array
myArray.sortByColumn('title', sortByLength); //sort by length of title attribute
function sortByLength(a,b) {
   return a.length - b.length;
}
myArray.sortByColumn('price',function(a,b){return a - b}); // sort by price

How it works

It runs the normal array.sort() method, but uses as its sort function a clever little function which picks out the values to be sorted by, creates a new test array out of these values and sorts it. Using the ternary operator, it checks if the test array is unchanged after this sort. If it is unchanged it means that the items in the original array are already in the right order so no change is made, otherwise they are swapped in the original array too.