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
}
]
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
}
]
Share
Improve this question
edited Jan 30, 2018 at 19:40
halfer
20.4k19 gold badges108 silver badges201 bronze badges
asked Jul 11, 2016 at 11:10
anubanub
5271 gold badge4 silver badges22 bronze badges
1
- 2 downvoted because you didn't provide any attempt (code snippets) to solve your problem – Maxim Shoustin Commented Jul 11, 2016 at 11:20
6 Answers
Reset to default 9You can do it using Array.prototype.filter()
Try like this
console.log(data.filter((x,i) => { return x.select; }).length)
DEMO
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 acplish the condition, so the values that have select true. Then you can count the values using truevalues.length
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;
}
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 bees the result returned to count.
This is not angular. This is straight JavaScript.
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
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;
};