0
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
4

3 回答 3

2

我不认为 udscore 可以按多个属性排序,但我已经使用普通的 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);
});

主要思想是在助手中。您需要根据属性优先级排序确保返回的值顺序正确。可能的值:11,10,1,0,-1,-10,-11。

于 2012-08-17T12:01:58.773 回答
1

使用http://linqjs.codeplex.com似乎适用于多次订购http://jsfiddle.net/andybooth/caQjf/

$scope.singleSortReversed = Enumerable.From(singleSort).OrderByDescending(orderByA).ToArray();   
$scope.multipleSortReversed = Enumerable.From(multipleSort).OrderByDescending(orderByA).ThenByDescending(orderByB).ToArray();

但是,使用 underscorejs 的解决方案仍然有用。我相信@cuzzae 建议的 [-item.a, -item.b] 仍然按错误的顺序返回项目,而不是按要求颠倒。

于 2012-08-17T11:29:43.930 回答
1

我一眼就能看到的是

var multipleSortReversedIterator = function(item) {
    return -[item.a, item.b]; // will return NaN
    // change to return [-item.a, -item.b];
}; 
于 2012-08-17T10:59:17.607 回答