Skip to content Skip to sidebar Skip to footer

Creating Stats Out Of Array With AngularJS

I have an array of objects looking like this: [ { 'date':'20/11/2014', 'time':'17.54.39', 'car':'369', 'driver':'Jenny', 'from':'Luna House', 'destination

Solution 1:

If you use lodash it's easier. This would be a way of doing it:

HTML:

  <body ng-app="myApp">
    <h1>Hello AngularJS!</h1>
    <div ng-controller="myCtrl">
      {{hello}}
      <pre>{{data | json}}</pre>
      <pre>{{data2 | json}}</pre>

      <div ng-repeat="(monthName, monthValue) in data2">
        <p class="month-header">{{monthName}}</p>
        <table ng-repeat="(groupName, groupValue) in monthValue">
          <tr>
            <th>{{groupName}}</th>
            <th>Trips</th>
            <th>Duration</th>
          </tr>
          <tr ng-repeat="(tripName, tripValue) in groupValue">
            <td>{{tripName}}</td>
            <td>{{tripValue.trips}}</td>
            <td>{{tripValue.duration}}</td>
          </tr>
        </table>
      </div>
    </div>
  </body>

JS:

  var dataByMonth = _.groupBy($scope.data, function(record) { return moment(record.date, 'DD-MM-YYYY').format('MMMM YYYY'); });
  console.log(dataByMonth);
  dataByMonth = _.mapValues(dataByMonth, function(month) {
   var obj = {};
   obj.Cars = _.groupBy(month, 'car');
   obj.Drivers = _.groupBy(month, 'driver');

   _.each(obj, function(groupsValue, groupKey) {
      obj[groupKey] = _.mapValues(groupsValue, function(groupValue) {
         return _.reduce(groupValue, function(sum, trip) {
           sum['trips']++;
         //addDuration(sum.duration, car.duration); 
         return sum;
         }, {trips: 0, duration: ''})
       });
   })

   return obj;
  });
 console.log(dataByMonth);

plunker


Post a Comment for "Creating Stats Out Of Array With AngularJS"