get count of items with some property in an array

The question:

I have an array of objects as follow.

$scope.students = [{'isSelected': true},
    {'isSelected': true},
    {'isSelected': false},
    {'isSelected': true},
    {'isSelected': true},
]

How can i get the count items that have isSelected property set to true ?

UPDATE:

The problem is $scope.students is fetched from a REST api and simply looping over the $scope.students variable does not work as the variable is undefined until the request is completed, and so the loop code errors out saying $scope.students is not defined.

I tried using $watch but in that case i have to define the loop under the watch directive and it only works one time when $scope.students is defined, after that the loop does not work as $scope.students itself is not changing.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

There is another way to do this: the AngularJS filters.
You can write this:

var selectedCount = $filter('filter')($scope.students, { isSelected: true }).length;

Method 2

You could also use javascript filter method (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)

$scope.selectedStudentsCount = function() {
  return $scope.students.filter(function(obj){return obj.isSelected}).length;
}

Method 3

You can add the following method to your controller. Variable selectedStudentsCount in your scope will keep number of all selected students (where isSelected is set to true).

Function counting selected users in angular.forEach will be executed only if studentsis not empty. Otherwise for empty students variable selectedStudentsCount will return 0.

$scope.selectedStudentsCount = function() {
    var count = 0;
    angular.forEach($scope.students, function(student){
        count += student.isSelected ? 1 : 0;
    });
    return count; 
}

Please note that selectedStudentsCount is a function so it will have to be called with () in your template e.g.

<h2>Total selected students: {{selectedStudentsCount()}}</h2>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment