I have an array of Object, I'm trying to reduce it to age group people and how many of them voted. on first loop it works good, on second loop accumulator becomes undefined and therefore I can't put anything in it.
this is my array of Object i'm looping over
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 },
];
and this is my function with the default accumulator object
function voterResults(arr) {
// your code here
arr.reduce(
(acc, person) => {
const type =
person.age >= 18 && person.age <= 25
? `Young`
: person.age <= 55
? `Mid`
: `Old`;
if (person.voted) {
acc[`num${type}People`]++;
acc[`num${type}VotesPeople`]++;
}
},
{
numYoungVotesPeople: 0,
numYoungPeople: 0,
numMidVotesPeople: 0,
numMidPeople: 0,
numOldVotesPeople: 0,
numOldPeople: 0,
}
);
}
I expect that every loop it will add the person to it's right age group and if he voted then it will add that to the age group voted counter. error is can't read from undefined even tho on first loop it works just fine.