Wrap the non-header rows in <tbody></tbody>
.
Then use Array#prototype.reduce() to scan the rows in reverse, treating the first (ie last) row as a special case :
$("table tbody tr").get().reverse().reduce(function(prevVal, tr, i) {
var $tds = $(tr).find('td'),
val = Number($tds.eq(1).text().replace(',',''))
diff = val - prevVal;
// console.log(val);
$tds.eq(2).text((i > 0) ? diff : '-');
$tds.eq(3).text((i > 0) ? ((100 * diff / prevVal).toFixed(1) + '%') : '-');
return val;
}, 0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Year</th>
<th>Total</th>
<th>Diff</th>
<th>Percentage</th>
</tr>
<tbody>
<tr>
<td>2017</td>
<td>80,000</td>
<td>?</td>
<td>?</td>
</tr>
<tr>
<td>2016</td>
<td>65,000</td>
<td>?</td>
<td>?</td>
</tr>
<tr>
<td>2015</td>
<td>59,000</td>
<td>?</td>
<td>?</td>
</tr>
<tr>
<td>2014</td>
<td>32,000</td>
<td>?</td>
<td>?</td>
</tr>
</tbody>
</table>
1
solved Difference between previous row