I am just setting out to learn JS and have been trying to get to grips with the reduce method recently - I have attempted an exercise where I must use the reduce method to count how many properties of an array of objects are true.
The code is as follows -
var 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}
];
function totalVoters(arr) {
arr.reduce((acc, item) => {
if (item.voted) {
acc = acc + 1
}
return acc
}, 0)
};
console.log(totalVoters(voters))
Currently the function returns 'undefined'. I got it to work without using a function but I'm also interested in getting all of my answers to work as functions.
I have used console.log on the if statement and it returns 7 true's and an undefined.. the 7 true's is correct but why is it also returning undefined as an 8th value? Furthermore, the function I wrote still calls on the parameter voted.. how do I access the voted object parameter without using it directly in my function?