我意识到这是在一段时间前提出的,但是我想我会添加我的解决方案。
此函数动态生成排序方法。只需提供每个可排序的子属性名称,并以+/-开头来表示升序或降序。超级可重用,并且不需要了解您放在一起的数据结构的任何知识。可以被当作白痴证明-但似乎没有必要。
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;}
}
}
}
用法示例:
items.sort(getSortMethod('-price','+ priority','+ name'));
这将按照items
从最低price
到最高的顺序进行排序,并与最高的项目建立联系priority
。该项目打破了其他纽带name
项目是一个数组,如:
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 } ...
];
现场演示:http: //gregtaff.com/misc/multi_field_sort/
编辑:修复了Chrome的问题。