I have this array of voters:
let voters = [
{name:'Bob' , age: 30, voted: true},
{name:'Jake' , age: 32, voted: true},
{name:'Kate' , age: 25, voted: false},
{name:'Sam' , age: 20, voted: false},
{name:'Phil' , age: 21, voted: true},
{name:'Ed' , age:55, voted:true},
{name:'Tami' , age: 54, voted:true},
{name: 'Mary', age: 31, voted: false},
{name: 'Becky', age: 43, voted: false},
{name: 'Joey', age: 41, voted: true},
{name: 'Jeff', age: 30, voted: true},
{name: 'Zack', age: 19, voted: false}
];
That I need to count how many voted (true).
I was able to find it using a for loop, but I'm learning the reduce method, and would like to apply it here but can't seem to figure out how.
// works perfectly
function totalVotes(voters){
let total = 0;
for (i=0; i < voters.length; i++){
if (voters[i].voted === true) {
total++
}
}
return total
}
function totalVotes2(voters){
voters.reduce(function (contador, item){
if (item.voted === true){
console.log(item)
console.log(contador)
//cant figure out how to make it count
}
// and how to return it
}, 0)
}