sum()

Sum the values in a data set.

Fairly simply, this plug-in will take the data from an API result set and sum it, returning the summed value. The data can come from any data source, including column data, cells or rows.

Note that it will attempt to 'deformat' any string based data that is passed into it - i.e. it will strip any non-numeric characters in order to make a best effort attempt to sum all data types. This can be useful when working with formatting numbers such as currency. However the trade-off is that no error is thrown if non-numeric data is passed in. You should be aware of this in case unexpected values are returned - likely the input data is not what is expected.

Plug-in code

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 );
} );

CDN

This plug-in is available on the DataTables CDN:

JS

Note that if you are using multiple plug-ins, it is beneficial in terms of performance to combine the plug-ins into a single file and host it on your own server, rather than making multiple requests to the DataTables CDN.

Version control

If you have any ideas for how this plug-in can be improved, or spot anything that is in error, it is available on GitHub and pull requests are very welcome!

Examples

// Simply get the sum of a column
  var table = $('#example').DataTable();
  table.column( 3 ).data().sum();
// Insert the sum of a column into the columns footer, for the visible
  // data on each draw
  $('#example').DataTable( {
    drawCallback: function () {
      var api = this.api();
      $( api.table().footer() ).html(
        api.column( 4, {page:'current'} ).data().sum()
      );
    }
  } );