Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs Remove duplicate elements in ng-repeat

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?

like image 397
Pawan Avatar asked Nov 26 '13 16:11

Pawan


People also ask

How do I remove duplicates in NG-repeat?

You can use unique filter while using ng-repeat . If you use track by $index then unique won't work. ok, I used unique and its working now, thanks!

What is Ng-repeat in AngularJS?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

How do I remove duplicate lines in files?

Remove duplicate lines with uniq If you don't need to preserve the order of the lines in the file, using the sort and uniq commands will do what you need in a very straightforward way. The sort command sorts the lines in alphanumeric order. The uniq command ensures that sequential identical lines are reduced to one.


1 Answers

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.

like image 58
Ben Lesh Avatar answered Sep 28 '22 17:09

Ben Lesh