Me doy cuenta de que esto fue preguntado hace un tiempo, pero pensé en agregar mi solución.
Esta función genera métodos de clasificación de forma dinámica. simplemente suministre cada nombre de propiedad de niño ordenable, antepuesto con +/- 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 ordenaría items
con el más bajo price
primero, con los vínculos que van al artículo con el priority
más alto. más lazos se rompen por el elemento name
donde los artículos 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/
EDIT: Solucionado el problema con Chrome.
la función de clasificación reacciona en el resultado positivo, negativo o cero. para que pueda escribir: "return aSize - bSize". será un código más simple y legible. –