Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get count of items with some property in an array

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.

like image 772
Amyth Avatar asked Mar 12 '13 11:03

Amyth


People also ask

How do you count elements in an array?

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.

Which property is used to count elements of an array?

The length property sets or returns the number of elements in an array.

How do you count the same object in an array?

To count the duplicates in an array:Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .


1 Answers

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

var selectedCount = $filter('filter')($scope.students, { isSelected: true }).length; 
like image 76
Samuele Furnari Avatar answered Sep 19 '22 16:09

Samuele Furnari