Aniruddha Bhondwe Aniruddha Bhondwe - 1 month ago 19
AngularJS Question

Angular JS grouping objects

I have the following array of objects:

$scope.monthTasks = [object,object,...,object];


Each object is as follows:

Object={
"emp_id": 1,
"task_id":212,
"project_id":2,
"task_name":"Updating UI",
"tasks": [
{
"task_date": "2016-9-14",
"hours": 2,
"minutes": 15
}
]
};
}


I have multiple such objects with the with different
task_date
. I want to group these objects by date as several tasks can have same the date. How can I achieve this?

Kei Kei
Answer

This is not such an easy way, but I would create dictionary whose key is task_date.
I assume that each object could have multiple tasks, which makes the problem more complex.
So my solution would be as follows:

http://codepen.io/kei-sato/pen/qaLRLZ

js:

var app = angular.module('myApp', []);

app.controller('myCtrl', ['$scope', function($scope){
  var monthTasks = [
    { id: 1, tasks: [{ task_date: '2016-9-13' }, { task_date: '2016-9-14' }] },
    { id: 2, tasks: [{ task_date: '2016-9-12' }] },
    { id: 3, tasks: [{ task_date: '2016-9-11' }, { task_date: '2016-9-14' }] },
    { id: 4, tasks: [{ task_date: '2016-9-10' }] },
  ];

  var monthTasksDict = monthTasks.reduce((dict, monthTask) => {
    monthTask.tasks.forEach(task => {
      var taskDate = task.task_date;
      dict[taskDate] = dict[taskDate] || [];
      dict[taskDate].push(monthTask);
    });
    return dict;
  }, {});

  var monthTasksWithTaskDate = Object.keys(monthTasksDict).map(taskDate => ({ task_date: taskDate, monthTasks: monthTasksDict[taskDate] }));
  $scope.monthTasksWithTaskDate = monthTasksWithTaskDate;

}]);

html:

<html lang="en" ng-app="myApp">
  <body ng-controller="myCtrl">
    <ul ng-repeat="monthTasks in monthTasksWithTaskDate | orderBy: 'task_date'">
      task_date: {{ task_date }}
      <li ng-repeat="monthTask in monthTasks">
        id: {{ monthTask.id }}
      </li>
    </ul>

    <!-- External Libraries -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  </body>
</html>