0
getTotalUserVotes = (userid) => {
  let posts = this.state.posts.slice();
  let current = posts.filter((item) => {
    return item.userid === userid;
  })
  console.log(current);
  const tot = current.map((item) => {
    return item.votes;
  })

  console.log("tot is " + tot) 
// this logs 50, 0 ,0 
//so each of the three posts that belong to that user have those amount
//of votes respectively.How can I add these? 
  return <div>votes: {tot}</div>;
}

When I have tried adding these using a for loop the strings concatenate so ill get 5000, I have searched how to stop that on stack overflow but none of the answers had little to any relation to my circumstance. somewhat related question.

an example of the data in posts is here

Omar
  • 3,401
  • 2
  • 23
  • 40

2 Answers2

1

You can use the reduce method instead of map to add each item's votes.

const tot = current.reduce((total, item) => total + Number(item.votes), 0);

However, you can actually filter, map and reduce all at once.

const getTotalUserVotes = (userid) => {

    const tot = this.state.posts.reduce((total, post) => {
        return post.userid === userid ? total + Number(post.votes) : total
    }, 0)

    return <div>votes: {tot}</div>;
}
Callam
  • 11,409
  • 2
  • 34
  • 32
  • Tried this implementation got TypeError: Reduce of empty array with no initial value – Omar Jan 01 '18 at 02:46
  • Updated my answer – Callam Jan 01 '18 at 02:47
  • This works. I looked at array reduce and I see that the optional parameter initial value is set to 0. Why do we need to do that? Why does it think the array is empty? – Omar Jan 01 '18 at 02:51
0

You can cast item.votes to a Number (since it sounds like it's stored as a String) and then use your for loop or reduce() to sum the values:

const tot = current.map((item) => {
  return Number(item.votes);
})

tot = tot.reduce((a,b)=>a+b,0)
thmsdnnr
  • 1,282
  • 10
  • 17
  • still get 5000 with this implementation – Omar Jan 01 '18 at 02:47
  • That's odd: this is the same implementation as Callam's, except this casts to number in the `map` instead of the `reduce`. const test = ['1', '2', '3'].map(i=>Number(i)); console.log(test.reduce((a,b)=>a+b,0)) // 6 – thmsdnnr Jan 01 '18 at 02:55