JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="//cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">
<script src="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th class="foo">Foo</th>
<th>Bar</th>
<th>Total</th>
<th>Sum</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button id="new-data">add new data to table</button>
<div><span>on first button click it has to insert new row at index 4 and updated sum on row at index 5(sum of row at index 4 + total of row index 5), on second click it has to update row 4 (sum up new bar value to existing bar value and update total and sum and sum of row 5) </span></div>
JavaScript
var data = [{"foo":0.003,"bar":30,"total":0.09,"sum":0.09},{"foo":0.005,"bar":300,"total":1.5,"sum":1.59},{"foo":0.006,"bar":280,"total":1.68,"sum":3.27},{"foo":0.007,"bar":150,"total":1.05,"sum":4.32},{"foo":1,"bar":100,"total":100,"sum":104.32}];
table = $('#example').DataTable({
data: data,
columns: [
{data: 'foo' , 'orderable': false },
{ data: 'bar' , 'orderable': false },
{ data: 'total', 'orderable': false },
{ data: 'sum', 'orderable': false }
],
order: [[0, 'asc']],
'preDrawCallback': function( settings ) {
var api = this.api();
var sortedArray = api.data().toArray();
sortedArray.sort(function(a, b) { return b.price - a.price });
var sum = 0;
for(var i = 0; i < sortedArray.length; i++) {
sortedArray[i].total = sortedArray[i].bar * sortedArray[i].foo;
sum += sortedArray[i].total;
sortedArray[i].sum = sum;
api.table().row(i).data(sortedArray[i]);
}
}
});
$('#new-data').click(function(){
var data = {"foo":0.008,"bar":10};
data.total = 0;
data.sum = 0;
var index = table.column('.foo').data().indexOf(data.foo);
console.log(index);
if(index == -1) {
table.row.add(data).draw();
} else {
var updatedData = table.row(index).data();
updatedData.bar += data.bar;
table.row(index).data(updatedData).draw();
}
});