How to sum values from one column based on a value from another column?
How to sum values from one column based on a value from another column?
Link to test case:
https://jsfiddle.net/17hmorck/1/
Debugger code (debug.datatables.net):
(15 tests complete. No failures or warnings found!)
Error messages shown:
(None)
Description of problem:
Hello!
I'm using Datatables on my project and i would like to sum salary column related with "pendent" status column. I'm trying to use "fnDrawCallback" but i'm not find a correct way to solve that:
HTML table:
<div id="status"></div>
<table id="example" class="display table" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>$320,800</td>
<td>Aproved</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>$320,800</td>
<td>Pendent</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
<th>Status</th>
</tr>
</tfoot>
</table>
And below are Datatable script that display data inside table and a fnDrawCallback script that showing the salary results:
$(document).ready(function() {
$('#example').DataTable({
"fnDrawCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Total over all pages
total = api
.column( 4 )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Update status DIV
$('#status').html('<b>TOTAL PENDENT SALARIES:</b> <u>$'+ total + '</u>');
}
});
});
Based on Datatables script above, how can i show inside a div tag a salary sum only related with "pendent" status? I did an example that exactly can describe my doubt: https://jsfiddle.net/17hmorck/1/. Thanks a lot
This question has an accepted answers - jump to answer
Answers
Use the
rows()
API with arow-selector
as a function to filter rows to a set that only containsPendent
. Usepluck()
to get the particular column data. Here is the updated example:https://jsfiddle.net/u3rky7tL/
Kevin
Thanks a lot for your feedback Kevin (@kthorngren). I saw your example and my table works as well