Skip to content

How do I calculate the average of the TR column in the table?

I would like to calculate the average of “TR” column in my table, but I could not calculate it using jquery.

my jquery code:

 table = $("#beyannameTable").DataTable(
             {
                dom: 'Bfrtip',
                buttons: ['excel', 'print'],
                lengthChange: false,
                searching: false,
                paging: false,

                "ajax": {
                    "url": "/Raporlama/ITH_Operasyon",
                    "type": "GET",
                    "datatype": "json",
                    data: { tescilTrh1: $("#tescilTrh1").val(), tescilTrh2: $("#tescilTrh2").val() },
                },

                "columns": [
                    { "data": "Kullanici" },
                    { "data": "Ref" },
                    { "data": "Tescil_No" },
                    { "data": "UNVAN" },
                    { "data": "TescilTarihi" },
                    { "data": "GumrukAdi" },
                    { "data": "Cekildi_Tarih" },
                    { "data": "GumrukEvraklar_Tarih" },
                    { "data": "TR" }
                ]
            });

Answer

You may access desired column data, using .column().data() method. If you need to recalculate your column average dynamically, based on visible rows, you may use selector modifier {search: 'applied'} as a second argument within .column() and option drawCallback to call average re-calculation upon each re-draw.

Please, checkout below demo of that approach:

//sample source data
const srcData = [
  {id: 1, name: 'Steve', age: 24},
  {id: 2, name: 'Chris', age: 31},
  {id: 3, name: 'Martha', age: 28},
  {id: 4, name: 'Sam', age: 33}
];
//DataTables initialization
$('#mytable').DataTable({
  dom: 'ft',
  data: srcData,
  columns: [
    {title: 'id', data: 'id'},
    {title: 'name', data: 'name'},
    {title: 'age', data: 'age'}
  ],
  drawCallback: () => $('#avgage').text(avgAge())
});
//average age calculation
function avgAge() {
  let columnData = $('#mytable').DataTable().column(2,{search:'applied'}).data().toArray();
  return Math.round(columnData.reduce((sum, item) => sum+=item)/columnData.length);
};
//Append <tfoot>
$('#mytable').append(`<tfoot><tr><td colspan="3">Average age: <span id="avgage">${avgAge()}</span></td></tr></tfoot>`);
<!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>