'How to print sum of a element in array in reactjs
I have data coming in from an api, it has a field called Amount, I have to display sum of all Amount.
This is how I am displaying all the amounts,
<div>
{orders.map(({ id, Amount }) => {
return (
<div key={id}>
<div>{Amount}</div>
</div>
)
})}
</div>
Solution 1:[1]
This is one way... there several ways..
const count = () => {
let total = 0;
orders.map( amount => total = total + amount)
console.log(total)
return(
<div>${total}</div>
)
};
Solution 2:[2]
I am just writing the pseudocode. If this is what you are asking for
const [sum,setSum]=useState(0);
<div>
{orders.map(({ id, Amount }) => {
setSum(sum+Amount)
return (
<div key={id}>
<div>{Amount}</div>
</div>
)
})}
<div>Sum={sum}</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | angelCanales |
Solution 2 | Ayushman Sinha |