Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculating sum of array objects in javascript , TypeError: parseInt(…).reduce is not a function

I have a array of objects with numbers but there type is string , I want to sum them all.

enter image description here

I’m doing this way as of previous answers on stack-overflow suggested.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// Here the data has an array of goods which contains
// amount objects and i want to calculate to sum of amount objects
Total Invoice Price:
{data.goods
   ? data.goods.map((item) => (
    <div key={item.id}>
     <div>{parseInt(item.amount).reduce((a, b) => a + b, 0)}</div>
       </div >
       ))
     : null}

But im getting error TypeError: parseInt(...).reduce is not a function , How to fix this ?

>Solution :

reduce is an array method. So: instead of mapping over the data, call a function within your JSX that returns the sum of the amount values of each object in the array.

Note: if your amount values are strings coerce them to numbers first (Number(good.amount)).

function Example({ data }) {

  function getTotal(data) {
    return data.goods.reduce((acc, good) => {
      return acc + Number(good.amount);
    }, 0);
  }

  return (
    <div>
      <h4>Total</h4>
      <p>{getTotal(data)}</p>
    </div>
  );

}

const data = { goods: [{ amount: '1' }, { amount: '5' }, { amount: '13' }] };

ReactDOM.render(
  <Example data={data} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading