Search code examples
angularjsangularjs-ng-repeatangular-filters

How can I group data with count of particular item in an Angular filter?


I have a list of players which belong to a group each. How can I use a filter to list the users per group? I need to get the output with correspong team count also

This is my script.js

angular.module('app',['angular.filter'])
  .controller('MainController', function($scope) { 

    $scope.players = [
      {name: 'A', team: 'alpha', score: 10},
      {name: 'B', team: 'beta', score: 14},
      {name: 'C', team: 'gamma', score: 8},
      {name: 'D', team: 'beta', score: 28},
      {name: 'E', team: 'gamma', score: 7},
      {name: 'F', team: 'beta', score: 28},
      {name: 'G', team: 'beta', score: 28},
      {name: 'H', team: 'alpha', score: 10},
      {name: 'I', team: 'beta', score: 28},
      {name: 'J', team: 'gamma', score: 7},
      {name: 'K', team: 'alpha', score: 10},
      {name: 'L', team: 'gamma', score: 7},
      {name: 'M', team: 'gamma', score: 7},
    ];

 });

this is my html file

  <body>
     <div ng-controller="MainController"> 
       <ul ng-repeat="(key, value) in players | groupBy: 'team'">
     Group name: {{ key }}
     <li ng-repeat="player in value">
       player: {{ player.name }} 
     </li>
     <li>score: {{value | map: 'score' | sum}}</li>
       </ul>
     </div>
  </body>

i need to get the output including the corresponding team count as

 Group name: alpha 3
 player: A
 player: H
 player: K
 score: 30

Group name: beta 5
 player: B
 player: D
    .
    .
    .
Group name: gamma 5
    .
    .
    .

alpha 3 beta 5 gamma 5 are the count of items


Solution

  • Just add the length of group to HTML like this {{ value.length }} .

    <body>
        <div ng-controller="MainController"> 
            <ul ng-repeat="(key, value) in players | groupBy: 'team'">
                Group name: {{ key }}  {{ value.length }} 
                <li ng-repeat="player in value">
                    player: {{ player.name }} 
                </li>
                <li>score: {{value | map: 'score' | sum}}</li>
            </ul>
        </div>
    </body>