我知道这个问题已经问过一段时间了,但我想添加我的解决方案。
该函数动态生成排序方法。只需提供每个可排序子属性的名称,以+/-作为前缀表示升序或降序。非常易于重用,并且不需要了解您组合的数据结构。可以制作成白痴式的 - 但似乎不必要。
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
进行排序,如果价格相同,则选择具有最高priority
的项目。如果优先级也相同,则通过项目的name
来进一步排列。
其中items
是类似于以下数组:
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问题。
col0
然后按col1
(升序)对对象数组进行排序:myArray.sort(function(a,b){return a.col0-b.col0||a.col1-b.col1});
另一个例子:按索引#0,#2,#1(降序)对数组的数组进行排序:myArray.sort(function(a,b){return b[0]-a[0]||b[2]-a[2]||b[1]-a[1]});
- ashleedawg