I have a array of objects with numbers but there type is string , I want to sum them all.
I’m doing this way as of previous answers on stack-overflow suggested.
// 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 ?
Advertisement
Answer
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>