AngularJs Remove duplicate elements in ng-repeat

Pawan picture Pawan · Nov 26, 2013 · Viewed 61.8k times · Source

I have one dictionary which is stored in field_detail

<li ng-repeat = "field in field_detail">{{field.displayName}}</li>

Now I dont want to include duplicate displayName of field_detail , what filter should I use?

Answer

Ben Lesh picture Ben Lesh · Nov 26, 2013

Just create a filter that gets the unique values, probably by a key. Something like this ought to do (I didn't test this at all, so I'll leave that business to you, this is just to give you an idea):

app.filter('unique', function() {
   return function(collection, keyname) {
      var output = [], 
          keys = [];

      angular.forEach(collection, function(item) {
          var key = item[keyname];
          if(keys.indexOf(key) === -1) {
              keys.push(key);
              output.push(item);
          }
      });

      return output;
   };
});
<div ng-repeat="item in items | unique: 'id'"></div>

Note: Array.indexOf() does not work in IE8, so if you're supporting IE8, you'll need to stub in indexOf(), or you'll need to use a slightly different approach.

Other thoughts: It's probably better just to create a filter that leverages the unique function in lowdash or underscore if you're already referencing those libraries.