Vikas Bansal Vikas Bansal - 4 months ago 104
Javascript Question

AngularJS: angular-filter: How to the group by with 2 columns?

I know I may sound a bit confusing so I request you to please let me elaborate

Note: A working POC (piece of code) has been attached to this post.

I have an array of an object having 3 properties
name


  1. name

  2. team

  3. team_rank




$scope.players = [
{name: 'Gene', team: 'alpha', team_rank: 1},
{name: 'George', team: 'beta', team_rank: 2},
{name: 'Steve', team: 'gamma', team_rank: 3},
{name: 'Paula', team: 'beta', team_rank: 2},
{name: 'Scruath', team: 'gamma', team_rank: 3}
];



I have got the result shown below in the pic by running the POC.

enter image description here

Problem

I need to show the rank of the team with the team name. Please suggest what should I do?



<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>

<meta name="description" content="[groupBy example]"/>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<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>
</ul>
</div>

<footer>
<script>
angular.module('app',['angular.filter'])
.controller('MainController', function($scope) {
$scope.players = [
{name: 'Gene', team: 'alpha', team_rank: 1},
{name: 'George', team: 'beta', team_rank: 2},
{name: 'Steve', team: 'gamma', team_rank: 3},
{name: 'Paula', team: 'beta', team_rank: 2},
{name: 'Scruath', team: 'gamma', team_rank: 3}
];
});
</script>
</footer>
</body>
</html>




Answer

If you're sure every player has the team_rank property, you can do:

Group name: {{ key }} Rank: {{value[0].team_rank}}

<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
  
<meta name="description" content="[groupBy example]"/>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div ng-controller="MainController"> 
    
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
  Group name: {{ key }} Rank: {{value[0].team_rank}}
  <li ng-repeat="player in value">
    player: {{ player.name }}
  </li>
</ul>
  </div>

<footer>
  <script>
angular.module('app',['angular.filter'])
  .controller('MainController', function($scope) { 
    $scope.players = [
      {name: 'Gene', team: 'alpha', team_rank: 1},
      {name: 'George', team: 'beta', team_rank: 2},
      {name: 'Steve', team: 'gamma', team_rank: 3},
      {name: 'Paula', team: 'beta', team_rank: 2},
      {name: 'Scruath', team: 'gamma', team_rank: 3}
    ];
 });
  </script>
</footer>
</body>
</html>