0

I have a array that needs to highlight duplicate values. This is what I have so far..

HTML

<tr ng-repeat="x in names | unique: 'names'" >
   <td>  {{ x }} </td>
</tr>

<style>
.duplicate{
background: yellow;

}
</style>

Controller:

 angular.module('myApp', []).controller('nameCtrl', function($scope) {
            $scope.names = [
                'Bob',
                'Dan',
                'Philip',
                'Philip',

            ];
        });

EDIT: In the example above "Philip" would be highlighted and would have duplicate class

3
  • what problem you are facing here ? Commented Feb 21, 2016 at 12:58
  • Please have a look at the update above. Commented Feb 21, 2016 at 13:03
  • first of all use that class="" in your tag or use ng-class="" Commented Feb 21, 2016 at 13:06

2 Answers 2

1

You can achieve it like this:

<div ng-app="MyApp">
  <div ng-controller="MyController">
    <table>
      <tr ng-repeat="name in names | unique">
        <td ng-class="{ 'duplicate': names.indexOf(name) !== names.lastIndexOf(name) }">{{name}}</td>
      </tr>
    </table>
  </div>
</div>

This applies the duplicate class for elements where the indexOf returns a different value than the lastIndexOf. This can only happen for items that are in the array more than once.

JSFiddle available here.

If you don't want to filter out the duplicates, you can use this:

<div ng-app="MyApp">
  <div ng-controller="MyController">
    <table>
      <tr ng-repeat="name in names track by $index">
        <td ng-class="{ 'duplicate': names.indexOf(name) !== names.lastIndexOf(name) }">{{name}}</td>
      </tr>
    </table>
  </div>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

I think this should work.

<tr ng-repeat="(key, count) in names | count" >
  <td ng-class="{your-highlight-class: count > 1 }">  {{ key }} </td>
</tr>

app.filter('count', function ( ) {
  return function (collection) {

    var result = {};
    collection.forEach( function( elm ) {

      if(!result[elm]) {
        result[elm] = 0;
      }

      result[elm]++;
    });

    return result;
  }
}]);

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.