【问题标题】:Angularjs: How to order an array based on a child array of object's Date fieldAngularjs:如何根据对象的日期字段的子数组对数组进行排序
【发布时间】:2018-02-14 07:07:07
【问题描述】:

我有一组对象数组,其结构如下:

parentArr = [
[{id:1, date:1505020200000}, {id:4, date:1505020200000 }],
[{id:2, date:1504681500000}],
[{id:3, date:1504671000000}, {id:20, date:1504671000000}]
]

每个子数组将只包含相同的日期。

我想要做的是使用 Angular 的 orderBy 过滤器将日期从最旧到最新排序,但我不确定如何去做。

我尝试将 orderby 过滤器设置为如下变量:

$scope.dateFilter= arr[0][0].date 
<div ng-repeat="child in parentArr | orderBy: dateFilter">

但我确定我做错了什么。

编辑:

非常感谢 Matthew 为我所做的所有工作,并且由于他的帮助,我意识到我需要做些什么。使用 array.sort 是我最终需要的数据结构。

$scope.results.sort(function (a, b) {
  return a[0].date - b[0].date;
});

【问题讨论】:

  • 试试orderBy: 'date'
  • @AaronCase 如果您找到了更直接的方法,提交您自己的答案并将其标记为 the 答案并没有什么坏处。干得好,祝你好运。

标签: javascript angularjs arrays sorting


【解决方案1】:

创建自定义过滤器以展平数组:

(function(app){
    app.filter("flatten", function() {
        return function(input) {
            var output = [];
            input.forEach(function(innerArr) {
                output = output.concat(
                    innerArr.map(function(obj) { return obj; })
                );
                return output;
            });
            return output;
        };
    });
}(angular.module("yourModule")));

那么你的ng-repeat就变成了:

<div ng-repeat="child in parentArr | flatten | orderBy: 'date'">

CodePen Demo

【讨论】:

  • 感谢马修的好例子。我看到你的过滤器在做什么,我意识到我没有完全正确地问我的问题。
  • 我得到了我需要的东西:$scope.results.sort(function (a, b) { return a[0].date - b[0].date; });
【解决方案2】:

添加一个 getter 函数来获取要排序的值。

$scope.myDateGetter = function(item) {
    return item[0].date;
}

然后将其作为表达式参数传递给 orderBy 过滤器。

<div ng-repeat="child in parentArr | orderBy: myDateGetter">

如此处所述:https://docs.angularjs.org/api/ng/filter/orderBy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2011-10-30
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多