function MyController($scope) {
var singleSort = [
{ "text": "Second", "a": 2 },
{ "text": "Fifth", "a": 5 },
{ "text": "First", "a": 1 },
{ "text": "Fourth", "a": 4 },
{ "text": "Third", "a": 3 }
];
var multipleSort = [
{ "text": "Second", "a": 1, "b": 2 },
{ "text": "Fifth", "a": 2, "b": 2 },
{ "text": "First", "a": 1, "b": 1 },
{ "text": "Fourth", "a": 2, "b": 1 },
{ "text": "Third", "a": 1, "b": 3 }
];
var singleSortIterator = function(item) {
return item.a;
};
var multipleSortIterator = function(item) {
return [item.a, item.b];
};
var singleSortReversedIterator = function(item) {
return -item.a;
};
var multipleSortReversedIterator = function(item) {
return -[item.a, item.b];
};
$scope.singleSort = _.sortBy(singleSort, singleSortIterator);
$scope.multipleSort = _.sortBy(multipleSort, multipleSortIterator);
$scope.singleSortReversed = _.sortBy(singleSort, singleSortReversedIterator);
$scope.multipleSortReversed = _.sortBy(multipleSort, multipleSortReversedIterator);
}
排序算法都与 multipleSortReversed 分开工作。这里有什么明显的错误吗?
http://jsfiddle.net/andybooth/QEBUx/
我得到的结果是
Single sort
First
Second
Third
Fourth
Fifth
Multiple sort
First
Second
Third
Fourth
Fifth
Single sort (reversed)
Fifth
Fourth
Third
Second
First
Multiple sort (reversed)
Second
Fifth
First
Fourth
Third
最佳答案
我不认为 uderscore 可以按多个属性排序,但我已经使用纯 JavaScript 排序函数实现了多重排序
var helper = function(x,y) {
var r = 0;
if(x.a > y.a) {r+=10;}
if(x.a < y.a) {r-=10;}
if(x.b > y.b) {r+=1;}
if(x.b < y.b) {r-=1;}
return r;
}
var asc = [{a:2,b:1},{a:1,b:2},{a:1,b:1},{a:2,b:2}].sort(function(x,y) {
return helper(x,y);
});
var desc = [{a:2,b:1},{a:1,b:2},{a:1,b:1},{a:2,b:2}].sort(function(x,y) {
return -1 * helper(x,y);
});
主要思想在helper中。您需要确保返回的值基于属性优先级排序的顺序正确。 可能的值:11,10,1,0,-1,-10,-11。
关于javascript 排序算法不起作用 - 有什么明显的我做错了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12004429/