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

4
  • Possible dublicate of stackoverflow.com/questions/15914658/… Commented May 20, 2015 at 11:30
  • You could use github.com/angular-ui/angular-ui-OLDREPO/blob/master/modules/… Commented May 20, 2015 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. Commented May 20, 2015 at 11:32
  • Just give me one example of you see a lots of examples around Commented May 20, 2015 at 11:34

2 Answers 2

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

4 Comments

is there any way to make it on javascript without the use of any other library ?
Why you don't try to give an example to your answers as Damien did. I don't understand the other links mentioned
It is much better and cleaner if you have this unique list prepared in the controller. Less headaches later.
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>

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.