繁体   English   中英

javascript排序算法不起作用-有什么明显的我做错了吗?

[英]javascript sorting algorithm not working - anything obvious i'm doing wrong?

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);   
}

排序算法都与multiSortReversed分开工作。 这里有什么明显的错误吗?

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);
});

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

我一眼就能看到的是

var multipleSortReversedIterator = function(item) {
    return -[item.a, item.b]; // will return NaN
    // change to return [-item.a, -item.b];
}; 

使用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]仍会以错误的顺序返回项目,而不是按要求反转。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM