1

I want to obtain the sum of total of votes using reduce(), but I am always receiving NaN as a result, instead of 20.

I have the following js code:

 const choiseArray=[
    {choice: "Shooter",url:"/questions/10/choices/01",votes:3},
    {choice: "Shooter2",url:"/questions/10/choices/02",votes:2},
    {choice: "Shooter3",url:"/questions/10/choices/03",votes:4},
    {choice: "Shooter3",url:"/questions/10/choices/03",votes:11},
];
const reducer = (accumulator, currentValue) => parseInt(accumulator.votes) + parseInt(currentValue.votes);

const totalVotes= choiseArray.reduce(reducer);

console.info(totalVotes);

Could you tell me what I am doing wrong and why?

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
  • 1
    `const reducer = (accumulator, currentValue) => accumulator + currentValue.votes;` and add a start value: `const totalVotes= choiseArray.reduce(reducer, 0);` – ASDFGerte Aug 08 '18 at 21:25
  • 1
    What's wrong is after first iteration accumulator is a number not object. Add a breakpoint and step through it to see – charlietfl Aug 08 '18 at 21:26
  • Why someone put -1, what is wrong with the question? – Ezequiel De Simone Aug 26 '18 at 22:12
  • 1
    Does this answer your question? [Array reduce function is returning NAN](https://stackoverflow.com/questions/39698450/array-reduce-function-is-returning-nan) – Sebastian Simon Apr 09 '21 at 14:23
  • Or better: [How to call reduce on an array of objects to sum their properties?](https://stackoverflow.com/q/5732043/4642212). – Sebastian Simon Apr 09 '21 at 14:35

1 Answers1

4

Your current problem is: In the first iteration, you have accumulator.votes + currentValue.votes, in the second, accumulator is now a number (the result of the calculation), not an object anymore, so it doesn't have the property votes, that's why you get NaN

Solution: Call your function passing 0 as reduce second parameter, this will be the accumulator, then in your function just sum values into it, not accessing accumulator.votes.

const choiseArray = [{
    choice: "Shooter",
    url: "/questions/10/choices/01",
    votes: 3
  },
  {
    choice: "Shooter2",
    url: "/questions/10/choices/02",
    votes: 2
  },
  {
    choice: "Shooter3",
    url: "/questions/10/choices/03",
    votes: 4
  },
  {
    choice: "Shooter3",
    url: "/questions/10/choices/03",
    votes: 11
  },
];
const reducer = (accumulator, currentValue) => accumulator + parseInt(currentValue.votes);

const totalVotes = choiseArray.reduce(reducer, 0);

console.log("Total Votes: " + totalVotes);
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48