I have created a table in React. I use javascript to map through an object that contains all the information I need to render a dynamic table. A couple of my columns contain numbers, and I want to sum those columns up to a given point in an additional column. Below is an example of my table.
The idea is that the balance column will total the entire debit column up to that point. So the balance cell on the first row should say 50 (like it does). However, the second cell in the balance column would need to say 100 (the sum of all cells in the debit column up to that point). Here is the react code I am using to map through the object (which is stored in state) to populate the table. Please note that the balance column is not stored in the object...I am attempting to have this column values created within the map function somehow.
<table id="transactionDetailDisplay">
<tr>
<th>#</th>
<th>Account</th>
<th>Description</th>
<th>Debit</th>
<th>Credit</th>
<th>Balance</th>
</tr>
{this.state.transactionObject.map((item =>
<tr>
<td>{}</td>
<td>{item.AccountID}</td>
<td>{item.Description}</td>
<td>{item.Debit}</td>
<td>{item.Credit}</td>
<td>{item.Debit}</td>
</tr>))}
</table>
What I would like to do is add a variable within my map function to serve as an accumulator. For example, rather than stating the last table data item as item.Debit, I would like to store item.Debit in a variable, then put that variable value in the table data line. With each cycle of the mapping function, I would add item.Debit to the variable to accumulate the correct sum to be displayed in Balance. However, I am having trouble figuring out the proper javascript to create a variable accumulator within the mapping function and / or the table tag. I think that since it is within the table tag, I cannot just define a variable like I could elsewhere. Is there a way I can do this, maybe with special syntax? Does anyone know any tricks to help me out? Thanks so much for any ideas!!