0

I'm working with AngularJS. I have an array of objects like this:

 $scope.documents =
   [
        {
            "id": "221",
            "activate": "t"
        },
        {
            "id": "1",
            "activate": "t"        
        },
        {
            "id": "2",
            "activate": "t"        
        },
        {
            "id": "221",
            "activate": "t"        
        },
        {
            "id": "5",
            "activate": "t"        
        },
        {
            "id": "221",
            "activate": "t"        
        },
        {
            "id": "221",
            "activate": "t"        
        },
        {
            "id": "7",
            "activate": "t"        
        },
        {
            "id": "8",
            "activate": "t"        
        },
        {
            "id": "9",
            "activate": "t"        
        },
        {
            "id": "221",
            "activate": "t"        
        }

    ]

I need an angularjs function to count the number of repeated values in the array of objects.

Something like this:

  $scope.count = function(param) {

    angular.forEach($scope.preguntas, function(value, key) {
        if (value.id == param){
        ........
        ........
        }
    });

  };

but I'm not sure how I can do.

I hope the result is something like this:

count(221);
5

Any of you have any suggestions please?

0

2 Answers 2

1

Just increment a count variable in your if statement and return it.

$scope.count = function(param) {
  var count = 0;

  $scope.documents.forEach(function(document) {
      if(document.id === param.toString() {
        count++;
      }
  });

  return count;
};

And your markup:

<div>{{count(221)}}</div>
Sign up to request clarification or add additional context in comments.

Comments

0

If you use lo-dash, you can do this:

_.countBy(documents, 'id')['221']

https://lodash.com/docs#countBy

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.