如何使用自定义排序顺序对角度js中的对象进行排序?

时间:2014-08-06 10:02:45

标签: javascript angularjs sorting

我希望以自定义排序方式显示对象属性的数组。以下是数组

$scope.weekDays = [
            {
                "day" : "TUESDAY",
                "count": 10
            },
            {
                "day" : "MONDAY",
                "count": 20
            },
            {
                "day" : "WEDNESDAY",
                "count": 30
            },
            {
                "day" : "SUNDAY",
                "count": 60
            }];

如果我们从weekDays开始打印,那就像星期二,星期一,星期三,星期日

但我希望在订单中显示" SUNDAY","星期一","星期五","星期二",&#34 ;星期三"

为此我做了以下

        $scope.orde = ["SUNDAY", "MONDAY", "FRIDAY", "TUESDAY","WEDNESDAY"];

        $scope.Sorted = [];

        $scope.SortCustomOrder = function() {
            var _c =0;
            for(var i = 0; i < $scope.orde.length; i++) {
                for (var _i = 0; _i < $scope.weekDays.length; _i++) {
                    if($scope.weekDays[_i].day==$scope.orde[i]) {
                        $scope.Sorted[_c] = $scope.weekDays[_i];
                        _c++;
                    }
                }
            }
        }; 

并打印$ scope.Sorted。它打印我说的。

有没有办法在angularjs中简单地使用这个或任何其他方法?

3 个答案:

答案 0 :(得分:1)

您可以使用内置的orderBy过滤器,如下所示:

app.controller('MainCtrl', function($scope, orderByFilter) {

  $scope.weekDays = [{
    "day": "TUESDAY",
    "count": 10
  }, {
    "day": "MONDAY",
    "count": 20
  }, {
    "day": "WEDNESDAY",
    "count": 30
  }, {
    "day": "SUNDAY",
    "count": 60
  }];

  var dateOrders = ["SUNDAY", "MONDAY", "FRIDAY", "TUESDAY", "WEDNESDAY"];

  $scope.Sorted = orderByFilter($scope.weekDays, function(item) {
    return dateOrders.indexOf(item.day);
  });
});

示例Plunker: http://plnkr.co/edit/IZfiavmZEpHf4hILdjQs?p=preview

答案 1 :(得分:0)

我已经让你成为了一名

的职员
$scope.weekDays = [
        {
            "id" : 3,
            "day" : "TUESDAY",
            "count": 10
        },
        {
            "id" : 2,
            "day" : "MONDAY",
            "count": 20
        },
        {
            "id" : 4,
            "day" : "WEDNESDAY",
            "count": 30
        },
        {
            "id" : 1,
            "day" : "SUNDAY",
            "count": 60
        }];
$scope.orderedWeekDays = $filter('orderBy')($scope.weekDays, 'id')

http://plnkr.co/edit/WdMQj7dJxuGsR2b9TRvZ?p=preview

答案 2 :(得分:0)

嗯,对于所有这样的排序和过滤操作,我通常会选择任何可用的库..

我强烈推荐这个:http://jscriptlinq.codeplex.com/ ..

对您的收藏品进行排序非常简单:

var arr = [{id: 'a', pos: 5},
    {id: 'd', pos: 2},
    {id: 'b', pos: 4},
    {id: 'c', pos: 3},
    {id: 'e', pos: 1}];

// col1 = ['e', 'd', 'c', 'b', 'a']
var col1 = $linq(arr)
    .orderBy(function (x) { return x.pos; })
    .select(function (x) { return x.id; })
    .toArray();

// col2 = ['a', 'b', 'c', 'd', 'e']
var col2 = $linq(arr)
    .orderBy("x => x.id")
    .select("x => x.id")
    .toArray();