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>
CodePudding user response:
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>
)
};
CodePudding user response:
This should be one possible way to achieve the desired objective (to render/display the sum of all Account
s.
<div>
{orders.map(({ id, Amount }) => {
return (
<div key={id}>
<div>{Amount}</div>
</div>
)
})}
Total: {
orders.reduce(
(t, {Amount}) => (t Amount),
0
)
}
</div>
Explanation
- Use
.reduce()
to iterate overorders
- Initialize the aggregator
t
to0
- De-structure the iterator to directly access the prop
Amount
- Use prefix
Amount
into aNumber
(in case it is a string)
CodePudding user response:
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>