Me doy cuenta de que esto se preguntó hace algún tiempo, pero pensé en agregar mi solución.
Esta función genera métodos de clasificación de forma dinámica. simplemente proporcione el nombre de cada propiedad secundaria clasificable, precedido de +/- para indicar el orden ascendente o descendente. Súper reutilizable y no necesita saber nada sobre la estructura de datos que ha reunido. Podría hacerse a prueba de idiotas, pero no parece necesario.
function getSortMethod(){
var _args = Array.prototype.slice.call(arguments);
return function(a, b){
for(var x in _args){
var ax = a[_args[x].substring(1)];
var bx = b[_args[x].substring(1)];
var cx;
ax = typeof ax == "string" ? ax.toLowerCase() : ax / 1;
bx = typeof bx == "string" ? bx.toLowerCase() : bx / 1;
if(_args[x].substring(0,1) == "-"){cx = ax; ax = bx; bx = cx;}
if(ax != bx){return ax < bx ? -1 : 1;}
}
}
}
ejemplo de uso:
items.sort (getSortMethod ('- precio', '+ prioridad', '+ nombre'));
esto se ordenaría primero items
con el más bajo price
, y los vínculos con el elemento con el más alto priority
. más lazos se rompen por el artículoname
donde elementos es una matriz como:
var items = [
{ name: "z - test item", price: "99.99", priority: 0, reviews: 309, rating: 2 },
{ name: "z - test item", price: "1.99", priority: 0, reviews: 11, rating: 0.5 },
{ name: "y - test item", price: "99.99", priority: 1, reviews: 99, rating: 1 },
{ name: "y - test item", price: "0", priority: 1, reviews: 394, rating: 3.5 },
{ name: "x - test item", price: "0", priority: 2, reviews: 249, rating: 0.5 } ...
];
demostración en vivo: http://gregtaff.com/misc/multi_field_sort/
EDITAR: problema solucionado con Chrome.