How to sum column based on values from another column

How to sum column based on values from another column

cipraencipraen Posts: 4Questions: 3Answers: 0

This is what I got so far. The code bellow works great to to the total sum for the values in column 1. How do I modify it to do the total for values in column 1 IF the value in column 2 is 'textA'.

$('#raport').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( 1 )
     .data()
     .reduce( function (a, b) {
       return intVal(a) + intVal(b);
     } ); 
   }
  });

Answers

  • cipraencipraen Posts: 4Questions: 3Answers: 0
    edited October 2015

    So I figured it out:

    // Total over all pages
              total = api
                  .cells( function ( index, data, node ) {
                            return api.row( index ).data()[1] === 'textA' ?
                                true : false;
                        }, 0 )
                  .data()
                  .reduce( function (a, b) {
                      return intVal(a) + intVal(b);
                  } );
    
This discussion has been closed.