One to many sum values on client side

One to many sum values on client side

Restful Web ServicesRestful Web Services Posts: 202Questions: 49Answers: 2

I am using a one-to-many join server side to get a set of values which I would like to display to the client as a 'total' numeric value.

"render": function ( data, type, full ) {
var total = 0;
return $.map( data, function ( d, i ) {
total += parseInt(d.amount, 10);
return total;   
});
}

This kind of works, but in a way that it returns each stage of the same rather than just the total. i.e. 300,500,740 instead of just 740

Does anyone know a method to sum these values in such a way that I just get the total?

Answers

  • Restful Web ServicesRestful Web Services Posts: 202Questions: 49Answers: 2

    Never mind! Adjusting the code slightly, as below, works now.

                    "render": function ( data, type, full ) {
                            var total = 0;
                            $.map( data, function ( d, i ) {
                                total += parseInt(d.amount, 10);
                            }); 
                            return total; 
                    } 
    
  • Restful Web ServicesRestful Web Services Posts: 202Questions: 49Answers: 2

    Actually, I do have one further question. Would it be possible to bring across a value from the main table and use it in a sum in this function? In the main table I have system.total_price in each table row. Could I bring this value into this function and use it in the equation in each row?

    I am struggling to figure out if I can access it in the scope?

  • Restful Web ServicesRestful Web Services Posts: 202Questions: 49Answers: 2

    I have figured out a working solution. Is this the best way to approach this?

    "render": function( data, type, row ) { 
    var total = 0;
    var total_price = parseInt(row.cms_module_system_bookings.total_price, 10);
    $.map( data, function ( d, i ) {
    total += parseInt(d.amount, 10);
    }); 
    total_price -= parseInt(total, 10);                         
    return '€' + total_price.toFixed(2); 
    }
    
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Looks valid to me. If data is an array then using a for loop would be faster than using $.maps.

    Allan

This discussion has been closed.