Reputation: 98
Let's say I have this array:
var foo = [{name: "one", number: 1},{name: "two", number: 2},{name: "three", number: 3}]
Now I want to output the sum of all numbers into a div. I came up with this:
var bar = 0
foo.map((n) => { bar = bar + n.number })
return(
<div>{bar}</div>
)
Is it possible/recommended to add up all the numbers just using the space between the div tags? <div>{here}</div>
Upvotes: 0
Views: 33
Reputation: 385
Use Array.reduce
<div>{foo.reduce((sum, i)=>sum+i.number, 0)}</div>
Upvotes: 1
Reputation: 371233
I'd use reduce
instead:
<div>{foo.reduce((a, { number }) => a + number, 0)}</div>
But while that's possible, I think that's a bit much to be putting into inline JSX. I'd slightly prefer to declare the total up above.
Upvotes: 2