Omar
Omar

Reputation: 3411

How to add items returned from map function

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

Upvotes: 0

Views: 92

Answers (2)

Callam
Callam

Reputation: 11539

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

Upvotes: 1

thmsdnnr
thmsdnnr

Reputation: 1302

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)

Upvotes: 0

Related Questions