Reputation: 89
How to group data by year and descending order (newer to older) and then inside each group sort items again by descending order?
I'm using angular and underscore.
fiddle link: http://jsfiddle.net/xgxfqrgv/1/
output now is:
2014
Cranberry
2015
Banana
Apple
but it should be:
2015
Apple
Banana
2014
Cranberry
html source:
<div ng-controller="MyCtrl">
<div ng-repeat="(year, fulldata) in all | orderBy: 'year':true">
<br>
<u>{{year}}</u>
<div ng-repeat="data in fulldata | orderBy: 'date':true">
{{data.name}}
</div>
</div>
</div>
js source:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
var _all = [
{ year: 2015, date: "1. 5. 2015", name: "Banana" },
{ year: 2014, date: "1. 10. 2014", name: "Cranberry"},
{ year: 2015, date: "1. 10. 2015", name: "Apple" }
];
$scope.all = _.groupBy(_all, 'year');
}
Upvotes: 0
Views: 2880
Reputation: 27976
The function _.groupBy returns an object and you can't order an object using ng-repeat. What you could do is transform the object into an array:
$scope.all = _.map( $scope.all, function(data, year){
return {
year: year,
data: data
}
})
and then have the following in the view (the minus before the year signifies a descending order):
<div ng-repeat="group in all | orderBy: '-year'">
<br>
<u>{{group.year}}</u>
<div ng-repeat="yearsdata in group.data | orderBy: 'date'">
{{yearsdata.name}}
</div>
</div>
Updated fiddle
Upvotes: 2
Reputation:
function MyCtrl($scope) {
var _all = [{
year: 2015,
date: "1. 5. 2015",
name: "Banana"
}, {
year: 2014,
date: "1. 10. 2014",
name: "Cranberry"
}, {
year: 2015,
date: "1. 10. 2015",
name: "Apple"
}];
$scope.all = _.groupBy(_all, 'year');
console.log($scope.all);
$scope.all[2015] = _.sortBy($scope.all[2015], 'date');
console.log($scope.all);
}
Note: instead of $scope.all[2015] = _.sortBy($scope.all[2015], 'date');
you should iterate over the properties of the object and apply the sorting. if you want to switch the sort order, just modify it to $scope.all[2015] = _.sortBy($scope.all[2015], 'date').reverse();
Upvotes: 0