Aaron Case
Aaron Case

Reputation: 95

Angularjs: How to order an array based on a child array of object's Date field

I've got an array of arrays of objects that has the following structure:

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

Each child array will only contain dates that are the same.

What I'm trying to do is use angular's orderBy filter to to order the dates from oldest to newest, but I'm unsure of how to do it.

I've tried setting the orderby filter to a variable like so:

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

but I'm sure I'm doing something wrong.

EDIT:

Thanks a bunch to Matthew for all his work helping me, and because of his help I realized what I needed to do. Using array.sort was what I ended up needing for my data structure.

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

Upvotes: 0

Views: 301

Answers (2)

Matthew Cawley
Matthew Cawley

Reputation: 2818

Create a custom filter to flatten the array:

(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")));

Then your ng-repeat becomes:

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

CodePen Demo

Upvotes: 1

JC Ford
JC Ford

Reputation: 7066

Add a getter function to get the value to sort by.

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

Then pass it to the orderBy filter as the expression argument.

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

As documented here: https://docs.angularjs.org/api/ng/filter/orderBy

Upvotes: 0

Related Questions