Home > Back-end >  How to print sum of a element in array in reactjs
How to print sum of a element in array in reactjs

Time:04-02

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 Accounts.

<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 over orders
  • Initialize the aggregator t to 0
  • De-structure the iterator to directly access the prop Amount
  • Use prefix to convert Amount into a Number (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>
  • Related