Reputation: 3411
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
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