Mi rendo conto che questo è stato chiesto tempo fa, ma ho pensato di aggiungere la mia soluzione.
Questa funzione genera dinamicamente metodi di ordinamento. fornire semplicemente ogni nome di proprietà figlio ordinabile, anteposto a +/- per indicare l'ordine crescente o decrescente. Super riutilizzabile e non ha bisogno di sapere nulla sulla struttura dati che hai messo insieme. Potrebbe essere una prova idiota, ma non sembra necessario.
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;}
}
}
}
utilizzo di esempio:
items.sort (getSortMethod ('- price', '+ priority', '+ name'));
questo ordina prima dal itemspiù basso price, con i legami che vanno all'elemento con il più alto priority. ulteriori legami vengono interrotti dall'articoloname
dove items è un array come:
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 } ...
];
demo live: http://gregtaff.com/misc/multi_field_sort/
EDIT: problema risolto con Chrome.