Reputation: 527
I have to get the count of boolean value (if it is true) in array of objects. The json structure is given below:
[
{
"id": 5,
"name": "a",
"select": true
},
{
"id": 3,
"name": "b",
"select": false
},
{
"id": 2,
"name": "x",
"select": true
},
{
"id": 1,
"name": "y",
"select": false
}
]
Upvotes: 3
Views: 11817
Reputation: 1
If you have a specific JSON structure which you have mentioned then you can try something like this. Can use arrow function if you want
const getResult = function(inputArr){
let result = [];
if( Object.prototype.toString.call(inputArr) === '[object Array]' && inputArr.length > 0 ){
result = inputArr.filter(function(item){
return item.select;
});
}
return result.length;
};
Upvotes: 0
Reputation: 25352
You can do it using Array.prototype.filter()
Try like this
console.log(data.filter((x,i) => { return x.select; }).length)
Upvotes: 9
Reputation: 1434
This is the functional programming way of doing it:
var count = yourarray.reduce((a, c) => c.yourboolvariable ? ++a : a, 0);
Explanation: The zero at the end is the initial value of a. a is known as the accumulator. The "reduce" function iterates through each value in the array, passing in the accumulator "a" as well is the current item "c". The right size of the fat arrow is the return value. If yourboolvariable value is true, it will add 1 to a and return that. If yourboolvariable value is false, it will simply return the previous value of a, ready to be passed in to the next iteration. The final value of a becomes the result returned to count.
This is not angular. This is straight JavaScript.
Upvotes: 1
Reputation: 1289
so , If it is response then you can use forEach loop like
$scope.count = 0;
angular.forEach(response, function(value, key) {
if (value.select == true) {
$scope.count = $scope.count + 1;
}
});
Then u can take $scope.count
from here
Upvotes: 0
Reputation: 5387
That should do the trick. no angular needed
function getTrueCount(array) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i].select) {
count++;
}
}
return count;
}
Upvotes: 1
Reputation: 894
You can do it using filter. The code would be:
var truevalues = yourarray.filter(function(element) {
return (element.select == true);
}
It returns the values that accomplish the condition, so the values that have select true. Then you can count the values using truevalues.length
Upvotes: 1