Datatable column average

Datatable column average

chakomachinchakomachin Posts: 1Questions: 1Answers: 0
edited August 2018 in Free community support

I´m trying to understand How could I Modify this code to obtain an average?? could you help me?

$(document).ready(function() {
    $('#example').DataTable( {
        "footerCallback": 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 );
 
            // Total over this page
            pageTotal = api
                .column( 4, { page: 'current'} )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
 
            // Update footer
            $( api.column( 4 ).footer() ).html(
                '$'+pageTotal +' ( $'+ total +' total)'
            );
        }
    } );
} );

http://datatables.net/release-datatables/examples/advanced_init/footer_callback.html

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @chakomachin ,

    That code just sums the totals. For an average, divide that total by the number of entries you counted...

    Cheers,

    Colin

This discussion has been closed.