Martin Ström
my-domain.se

Multi-dimensional array sorter

The other day when working on some small updates on konst-teknik.se I wanted to sort the projects in a multi dimensional way, and take the other factors than the first into account. JavaScript’s Array#sort only supports one dimensional sorting so I wrapped my own sorter.

The results turned up pretty good (at least compared to the first test), or perhaps I just like recursing functions.



var sortOrder = {
  'cat-no': ['cat-no', 'name', 'type', 'year'],
  'name':   ['name',   'type', 'year', 'cat_no'],
  'year':   ['year',   'name', 'type', 'cat_no'],
  'type':   ['type',   'name', 'year', 'cat_no']
};

function sort(order) {
  var ordering = sortOrder[order], length = ordering.length;
  $$('#projects > li').sort(function(left, right) {
    left = Project.find(left), right = Project.find(right);
    return (function(index) {
      var a = left.getSortValue(ordering[index]),
          b = right.getSortValue(ordering[index]);
      return a < b ? -1 : a > b ? 1 :
        index < length ? arguments.callee(++index) : 0;
    })(0);
  }).each(function(project) {
    project.parentNode.appendChild(project);
  });
}


CSS is in progress