1

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.

1 Answer 1

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.