reichenwald
reichenwald

Reputation: 98

How to add up the values of a single property in an object array?

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

Answers (2)

Sumedh Chakravorty
Sumedh Chakravorty

Reputation: 385

Use Array.reduce

<div>{foo.reduce((sum, i)=>sum+i.number, 0)}</div>

Upvotes: 1

CertainPerformance
CertainPerformance

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

Related Questions