user7046311 user7046311 - 1 month ago 8
AngularJS Question

In AngularJS, is there a way to know that there is duplicate in the data.location, and only output once for each unique data.location

In AngularJS, is there a way to know that there is duplicate in the data.location, and only output once for each unique data.location.
I.e. Instead of the following:

A Jane
A Tom
B Brian
B Jane
B Mike
R Donald
R Jerry


would prefer expected output to be:

A Jane
Tom
B Brian
Jane
Mike
R Donald
Jerry


The angular code as follows:

<body ng-app="app" ng-controller="ctrl">
<table>
<tr ng-repeat="data in output " >
<td ng-bind="data.location"> </td>
<td ng-bind="data.name"></td>
</tr>
</table>
<script>
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.output = [
{name: "Jane ", location: "A"},
{name: "Tom", location: "A"},
{name: "Brian", location: "B"},
{name: "Jane", location: "B"},
{name: "Mike", location: "B"},
{name: "Donald", location: "R"},
{name: "Jerry", location: "R"}
] ;
});



Answer

angular.module('app', [])
   .controller('ctrl', function($scope) {
     $scope.output = [{
       name: "Jane ",
       location: "A"
     }, {
       name: "Tom",
       location: "A"
     }, {
       name: "Brian",
       location: "B"
     }, {
       name: "Jane",
       location: "B"
     }, {
       name: "Mike",
       location: "B"
     }, {
       name: "Donald",
       location: "R"
     }, {
       name: "Jerry",
       location: "R"
     }];
     
     var reduced = {};
   
     $scope.output.map(function(item){
         reduced[item.location] = reduced[item.location] || [];
         reduced[item.location].push(item.name);
     });
   
     $scope.reducedOutput = reduced;
   });
table, td{
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app" ng-controller="ctrl">
  <table>
    <tr ng-repeat="(key, value) in reducedOutput">
      <td ng-bind="key"></td>
      <td>
        <ul>
          <li ng-repeat="val in value" ng-bind="val"></li>
        </ul>
      </td>
    </tr>
  </table>
</body>