'Datatable sum column by row grouping and show sum result at the end of each group

I am using datatable row grouping from https://datatables.net/examples/advanced_init/row_grouping.html and it works fine.

I have following scenario: enter image description here

Now I want to calculate sum(sub-total) by each grouping abd show result in row at the end of grouping as you see in image.

At the end of listing , want to show a final row of total amount. How to accomplish that.

Js used code is:

$(function() {
    var table = $('#table').DataTable({
    "columnDefs": [
        { "visible": false, "targets": 1 }
    ],
    "order": [[ 1, 'asc' ]],
    "displayLength": 25,
    "drawCallback": function ( settings ) {
        var api = this.api();
        var rows = api.rows( {page:'current'} ).nodes();
        var last=null;

        api.column(1, {page:'current'} ).data().each( function ( group, i ) {
            if ( last !== group ) {
                $(rows).eq( i ).before(
                    '<tr class="group" style="background-color:#F5F5F5;"><td colspan="3">'+group+'</td></tr>'
                );

                last = group;
            }
        } );
    }
    });
});


Solution 1:[1]

For the same exemple here : https://datatables.net/examples/advanced_init/row_grouping.html

I have made some changes inside "drawCallback": function ( settings ) {

Check this fiddle https://jsfiddle.net/bLykqbo6/110/

I hope it helps

Solution 2:[2]

  "drawCallback": function ( settings ) {
    var api   = this.api();
    var rows  = api.rows( {page:'current'} ).nodes();
    var last  = null;     
    var sum   = 0;
    var groupColumn = 1; //index of column which you are going to group by.
    var amtColumn   = 3; // index of column which you are going to sum.
    api.column(groupColumn, {page:'current'} ).data().each( function ( group, i ) {
      if ( last !== group ) {
        api.rows().data().each( function(item){
          if (item[groupColumn] == group){
            sum = sum + (+item[amtColumn]);
          }
        });
        $(rows).eq( i ).before(
          '<tr class="group"><td colspan="2" style="background-color: #e7e7e7;"><b>'+group+'</b></td><td style="background-color: #e7e7e7;"><b>'+ sum +'</b></td></tr>'
        );
        last = group;
        sum  = 0;
      }
    });
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hassan absike
Solution 2 sakthi s