1

I'm looking for a way on how to avoid showing duplicate values when using ng-repeat for Angular JS.

I have a JSON list which look like :

[
{
"Country":"Algeria",
"Value":"200"
},
{
"Country":"France",
"Value":"300"
},
{
"Country":"France",
"Value":"600"
},
]

and my JS code to show countries :

<a class="item" href="#" ng-repeat="item in items">
    {{ list.country }}
  </a>

Is possible to use ng-if or any condition code to don't show duplicate items ?

to show only : Algeria France in my example

Yasser B.
  • 835
  • 6
  • 20
  • 34
  • Possible dublicate of http://stackoverflow.com/questions/15914658/angular-js-how-to-make-ng-repeat-filter-out-duplicate-results – micnil May 20 '15 at 11:30
  • You could use https://github.com/angular-ui/angular-ui-OLDREPO/blob/master/modules/filters/unique/unique.js – Reena May 20 '15 at 11:30
  • You should do this in Javascript, not in the view. This is the sort of logic that shouldn't pollute your view. Just search for a Javascript unique function, there are lots of examples around. – garryp May 20 '15 at 11:32
  • Just give me one example of you see a lots of examples around – Yasser B. May 20 '15 at 11:34

2 Answers2

4

The best solution is to clean data before the templating, especially if you want the France value is 900 (the addition of the two duplicates).


If you want display only one of the two duplicates you can use a unique function such as : https://lodash.com/docs#uniq

Or with native javascript :

In your javascript :

var values = [ {
    "Country": "Algeria",
    "Value": "200"
}, {
    "Country": "France",
    "Value": "300"
}, {
    "Country": "France",
    "Value": "600"
} ];

function onlyUnique( value, index, self ) {
    return self.indexOf( value ) === index;
}

var uniqueValues = values.filter( onlyUnique );

In your template :

<a class="item" href="#" ng-repeat="value in uniqueValues">
    {{ value.country }}
</a>

But if you still want to do this in the template, you can check if the index of the iteration is the same as the index of the item in the array :

<a class="item" href="#" ng-repeat="item in items" ng-if="$index === items.indexOf(item)">
    {{ list.country }}
</a>
Damien
  • 3,915
  • 1
  • 17
  • 18
0

You could try this: http://angular-ui.github.io/ui-utils/

<a class="item" href="#" ng-repeat="item in items | unique:'country'">
    {{ list.country }}
  </a>
Reena
  • 1,109
  • 8
  • 16