Scott
Scott

Reputation: 2760

Datatables (jQuery) - sum ALL rows

I have the following, which successfully counts up the total of row on a SINGLE page of a datatable. How do I get the sum off ALL rows in the group, rather than just the ones on any single page?

rowGroup: {
        dataSrc: 0,

        startRender: function (rows, group) {
            var sum = rows
                .data()
                .pluck(3)
                .reduce(function (a, b) {
                    return a + b * 1;
                }, 0);

            return $('<tr/>')
                .append('<td colspan="3">' + group + ' - Total Coverages: ' + sum + '</td>')
        }

  .append('<td colspan="3">' + group + ' - Coverages: ' + totCov + '</td>')
    },

Upvotes: 1

Views: 2889

Answers (1)

K Thorngren
K Thorngren

Reputation: 548

My understanding is the rows parameter in startRender and endRender cover only those rows displayed on the current page. If you want to calculate all rows then you will need to use filter() to filter the table based on the group and calculate the sum. Here is an example:

    rowGroup: {
      endRender: function ( rows, group ) {
        var filteredData = $('#example').DataTable()
          .rows()
          .data()
          .filter( function ( data, index ) {
            return data[2] == group ? true : false;
          } )
          .pluck(5)
          .sum();
        return group +' ('+rows.count()+' rows on page, $' + filteredData + ' salary total all pages)';
    },
        dataSrc: 2
    }

Basically it filters column 2 and then sums column 5 from the filtered rows. It displays the number of rows in the current page and the total salary, for the group, over all the pages.

The sum() method comes from the sum() plug-in. You can see the example here: http://live.datatables.net/fazigehi/1/edit

Upvotes: 3

Related Questions