Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show unique items with count of duplicate occurrences in ng-repeat

I have a below JSON:

[{"brand":"abc"},{"brand":"xyz"},{"brand":"abc"},{"brand":"abc"},{"brand":"por"},{"brand":"xyz"}]

Using ng-repeat, How can I display like -

Brand Occurances
abc      (3)
xyz      (2)
por      (1)

i.e. brand name (number of duplicate occurrences of same brand name)?

like image 899
AngryJS Avatar asked Jan 19 '26 11:01

AngryJS


1 Answers

You can create a custom function which will be returning the count from the existing array with the repeatvie values (occurances)

Along with the filter to show the unique values from the JSON:

$scope.getCount = function(i) {
    var iCount = iCount || 0;
    for (var j = 0; j < $scope.brands.length; j++) {
      if ($scope.brands[j].brand == i) {
        iCount++;
      }
    }
    return iCount;
  }

AND a filter will look like this:

app.filter('unique', function() {

  return function (arr, field) {
    var o = {}, i, l = arr.length, r = [];
    for(i=0; i<l;i+=1) {
      o[arr[i][field]] = arr[i];
    }
    for(i in o) {
      r.push(o[i]);
    }
    return r;
  };
})

Working Plunkr

like image 112
Dhaval Marthak Avatar answered Jan 22 '26 07:01

Dhaval Marthak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!