Yasser B.
Yasser B.

Reputation: 835

How to do not show duplicate values Ng-repeat Angular JS

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

Upvotes: 1

Views: 3249

Answers (2)

Reena
Reena

Reputation: 1119

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>

Upvotes: 0

Damien
Damien

Reputation: 4093

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>

Upvotes: 4

Related Questions