user13286
user13286

Reputation: 3075

Listing out unique value from JSON data in AngularJS

Let's say I have a set of JSON data for products. Each product has a category assigned to it. How could I go about listing out all of the categories but only displaying each category once. Here's what I have currently which lists out all categories, including duplicates:

(function() {
    var app = angular.module('store', []);
    app.controller('StoreController', ['$scope', function($scope) {
      var vm = this;
      
      $scope.products = [{
        "category": "Cat1",
        "name": "Product1"
      }, {
        "category": "Cat1",
        "name": "Product2"
      }, {
        "category": "Cat2",
        "name": "Product3"
      }, {
        "category": "Cat3",
        "name": "Product4"
      }]
   }]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html lang="en" ng-app="store">
<body ng-controller="StoreController as vm">
<div ng-repeat="product in products" class="category">
  <button>{{product.category}}</button>
</div>
</body>
</html>

So I want Cat1 to only be displayed once.

Upvotes: 1

Views: 49

Answers (1)

tymeJV
tymeJV

Reputation: 104795

You could get a list of unique categories like:

$scope.uniqueCategories = Object.keys($scope.products.reduce(function(categoryMap, product) {
    categoryMap[product.category] = 1;
    return categoryMap;
}, {})); //["Cat1", "Cat2", "Cat3"]

Upvotes: 2

Related Questions