Skip to content Skip to sidebar Skip to footer

Position Table Rows According To Their Dataset Value

I am working on a sortable table. Every column has a button for giving each row a respective data-position value. For example, by clicking on a button for sorting rows in ascending

Solution 1:

Here is how I've sorted tables. I hope you can follow and see what it does and modify for your use.

// TableSortfunctionsortTable(tableElement, firstRow, colIndex, colType, reverseSort, toFixed2) {
  var rowColValue=[];
  for(var r=firstRow;r<tableElement.tBodies[0].rows.length;r++) {
    var rowId="row"+r.toString();
    tableElement.tBodies[0].rows[r].id=rowId;
    var cellValue=tableElement.tBodies[0].rows[r].cells[colIndex].innerText;
    if(colType=="Number") {
      if(cellValue=="—") cellValue="";
      elseif(toFixed2) {
        if(cellValue.includes(".")) {
          if(cellValue.split(".")[1].length==1) tableElement.tBodies[0].rows[r].cells[colIndex].innerText+="0";
        } else {
          tableElement.tBodies[0].rows[r].cells[colIndex].innerText+=".00";
        };
      }
      cellValue=Number(cellValue.split(",").join(""));
    }
    rowColValue.push([rowId, cellValue]);
  }
  rowColValue.sort((a, b) => {
    var retVal=0;
    if(a[1]<b[1]) retVal=-1;
    elseif(a[1]>b[1]) retVal=1;
    return retVal;
  });
  if(reverseSort) rowColValue.reverse();
  for(var rcv=0;rcv<rowColValue.length;rcv++) {
    tableElement.tBodies[0].rows[0].parentNode.appendChild(document.getElementById([rowColValue[rcv][0]]));
  }
}

Table element is the table id or document.getElementById("table-id-here"). First row: use 1 (if I remember correctly) if there is a heading, and 0 if there isn't. Col index:... Col type: if number, takes care of mixed 2, 2.0, 2.00... reverseSort: true or false... to fixed2: true or false for numbers from 7 to 7.00, 2.4 to 2.40, etc. Basically, appending an existing row sends it to the bottom.

Post a Comment for "Position Table Rows According To Their Dataset Value"