javascriptfiltersumvisible

Summing up filtered html columns takes to much time, how to speed it up?


With my very basic "knowledge" in javascript I have written the following generic function to sum up filtered columns (i.e. the content of the visible <td> elements of a filtered column). The unfiltered table has about 2000 lines and 55 columns. The function has the following parameters:

The function is executed as soon as selection via dropdown in the html-table is made (on change).

The problem is that it takes to much time (about 1-2 mins) until I get the result. Is there a solution (which I can understand) that performs quicker?

As the page itself as the table are created dynamically I can only provide screenshots. Hope that helps for better understanding?

screenshot 1, screenshot 2, screenshot 3

function htmlTableColSum(tabID, colNum, colS, rec) {
  var table = document.getElementById("" + tabID + "");
  var sumCol = 0;
  let count = $('#' + tabID + ' tbody tr').length;

  for (var i = 1; i < count - 1; i++) {
    if ($('#' + tabID + ' tbody tr:eq(' + i + ')').is(':visible')) {
      if (table.rows[i].cells[colNum].innerHTML !== "") {
        sumCol = sumCol + parseInt(table.rows[i].cells[colNum].innerHTML);
      }
    }
  }
  
  sumCol = sumCol / rec;
  if (rec > 1) {
    sumCol = sumCol.toFixed(2)
  }
  
  document.getElementById("" + colS + "").innerHTML = "" + sumCol;
}

Solution

  • You could try the following. Same principal just some code performance changes

    function htmlTableColSum(tabID, colNum, colS, rec) {
      var sumCol = 0;
      var visibleRows = $('#' + tabID + ' tbody tr:visible');
      var count = visibleRows.length;
    
      visibleRows.each(function(i, row) {
        var cellValue = row.cells[colNum].innerHTML;
        if (cellValue !== "") {
          sumCol += parseInt(cellValue);
        }
      });
    
      sumCol /= rec;
      if (rec > 1) {
        sumCol = sumCol.toFixed(2);
      }
    
      document.getElementById(colS).innerHTML = sumCol;
    }
    

    That being said there is no way for me to physically test this without some sort of mock data set to populate the DOM to do any tests.