Nick T
Nick T

Reputation: 683

Datatables- Getting the total when there are null values

I'm using DataTables to calculate the all of the rows in the column and display the total in the footer of the table.

Here's the problem: It appears that whenever there is a null value in any of the rows of the column that I'm calculating, the total gets displayed as NaN.

How can I get DataTables to ignore the null values in the column and just total up the non-null values?

<div align="center">
     <table id = 'mytabl' class="display compact nowrap">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
    {% for num in numberdata.mytable_set.all %}
        <tr>
            <td>{{ num.col1 }}</td>
            <td>{{ num.col2 }}</td>
        </tr>
    {% endfor %}
    </tbody>
         <tfoot>
                <tr>
                    <th></th>
                    <th></th>
                </tr>
         </tfoot>
    </table>
            <script>
            $(document).ready(function() {
              $('#mytabl').DataTable({
                "searching": true,
                "pageLength": 40,
                "scrollX": true,
                "paging": false,
                "info": false,
                drawCallback: () => {
                  const table = $('#mytabl').DataTable();
                  const tableData = table.rows({
                    search: 'applied'
                  }).data().toArray();
                  const totals = tableData.reduce((total, rowData) => {
                    total[0] += parseFloat(rowData[1]);
                    total[1] += parseFloat(rowData[2]);
                    return total;
                  }, [0, 0]);
                  $(table.column(1).footer()).text(totals[0]);
                  $(table.column(2).footer()).text(totals[1]);
                }
              })
            });
            </script>

Upvotes: 0

Views: 571

Answers (1)

Dave Keane
Dave Keane

Reputation: 737

const totals = tableData.reduce((total, rowData) => {
                total[0] += rowData[1] ? parseFloat(rowData[1]) : 0;
                total[1] += rowData[2] ? parseFloat(rowData[2]) : 0;
                return total;
              }

How bout this if the value is null add zero

Upvotes: 1

Related Questions