luke luke - 25 days ago 10
Javascript Question

Filter out duplicates in ng-repeater but increment value next to the item

I have a filter which is currently removing duplicates in an ng-repeater that I have. I need to be able to show the value amount that is in the array next to the value.

E.g. If I had an array [ 'houston', 'houston', 'dallas' ]

The values on the page would look like: houston (2), dallas (1)

I thought I had a solution but I am getting angular error because I was returning an array instead of the original items I had. I was basically pushing item into the array as [item, 1] where one is the number of times it has been seen. And I would create an else part of the if statement where I would increment that amount but no go.

Need some ideas of how to get this working.

Here is the filter I created

.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;
};
});


Here is the ng-repeater with my filter on it. (Note I have added {{ value }} where I need the number of items to go)

<li ng-repeat="info in search.hits | unique: 'type'">
<a>{{ info.type }} {{ value }}</a>
</li>


Thanks!

Answer

That's very simple .

Add a counter like this

.filter('unique', function() {
  return function(collection, keyname) {
    var output = [];
    angular.forEach(collection, function(item) {
      var obj = output.filter(function(x) {
        return x[keyname] == item[keyname];
      });
      if (obj.length > 0)
        obj.count += 1;
      else {
        item.count = 1;
        output.push(item);
      }
    });
    return output;
  };
});

View:

<li ng-repeat="info in search.hits | unique: 'type'">
  <a>{{ info.type }} {{ info.count || 0 }}</a>
</li>