How to summarize multiple columns

How to summarize multiple columns

smasonsmason Posts: 25Questions: 11Answers: 0

I have the code on this page working:
https://datatables.net/examples/advanced_init/footer_callback.html

However I don't understand how to summarize multiple columns, the example just summarizes one. I have a table where I want to summarize 3 columns and average a final column. How is that accomplished?

This question has an accepted answers - jump to answer

Answers

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395

    The function you have copied refers to "column( 4 )" throughout. You could rewrite it to accept a variable column number as a passed parameter.

  • smasonsmason Posts: 25Questions: 11Answers: 0

    Yes, I understand that it uses column(4) throughout. My javascript skills are not good enough to know how to make that a dynamic variable which is why I needed help with that snippet.

    But anyhow I solved this issue a different way:
    First use the SUM Plugin Declare it before the datatable initialization but inside document ready block:

    // SUM PLUGIN
        jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
            return this.flatten().reduce( function ( a, b ) {
                if ( typeof a === 'string' ) {
                    a = a.replace(/[^\d.-]/g, '') * 1;
                }
                if ( typeof b === 'string' ) {
                    b = b.replace(/[^\d.-]/g, '') * 1;
                }
    
                return a + b;
            }, 0 );
        } );
    

    Now the footer callback inside the datatable definition looks like this:

    "footerCallback": function () {
        var api = this.api(),
        columns = [2, 3, 4]; // Add columns here
    
        for (var i = 0; i < columns.length; i++) {
        //summarize only the visible columns
            $('tfoot th').eq(columns[i]).html('' + api.column(columns[i], { filter: 'applied', page: 'current' }).data().sum());
        }
    } //end footerCallback
    
  • allanallan Posts: 64,379Questions: 1Answers: 10,628 Site admin
    Answer ✓

    That's perfect and exactly what tangerine was suggesting.

    Nice one :smile:

    Allan

This discussion has been closed.