0

i'm not quite understanding the .reduce() method

i've tried tinkering with the code a bit, i can see that the acumulator increments on the first case but then turns to 'undefined' and ' NaN on subsequent iterations. not sure why the value isn't accumulating when val.voted === true.

function totalVotes(arr) {
  return arr.reduce((acc, val) => { val.voted === true ? acc+=1 : acc;}, 0); 

}

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}
];
console.log(totalVotes(voters)); // 7

result should be 7..

DBN
  • 125
  • 1
  • 10

2 Answers2

4

Your callback function must return a value for the accumulator during the next iteration. Currently, you don't have a return, so execution falls through and returns undefined on the first call. To fix this, simply add return:

function totalVotes(arr) {
  return arr.reduce((acc, val) => { return val.voted === true ? acc+=1 : acc;}, 0); 

}

Alternatively, you can remove the braces, since you are using fat arrow syntax:

function totalVotes(arr) {
  return arr.reduce((acc, val) => val.voted === true ? acc+=1 : acc, 0); 

}
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
1

You need a return statement with a block statement.

A shorter approach would be just to add the boolean value.

function totalVotes(arr) {
    return arr.reduce((sum, { voted }) => sum + voted, 0); 
}

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 }];

console.log(totalVotes(voters)); // 7
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392