Skip to content Skip to sidebar Skip to footer

How To Sort The Table To Order By Points At End Of Column Using Javascript

I am trying to sort the table using javascript to order by total points at the end. The table is a dynamic one so W1, W2, W3 columns adds up to total. Is there way to order rows th

Solution 1:

can you gather the cells into object and sort them like this. https://jsfiddle.net/e4oscnz8/4/

constsortTotal = () => {
  const tbl = [...document.getElementsByClassName("fl-table")][0];
  const tbody = [...tbl.tBodies][0];
  const oObjects = [];

  [...tbody.rows].forEach(row => {
    const cells = [...row.cells];
    const obj = [...row.cells].map(cell => {
        return cell.innerHTML;
    });
    oObjects.push(obj);
  });

  oObjects.sort((a, b) => a[a.length -2] > b[b.length -2] ? 1 : -1);

  [...tbody.rows].forEach((row, i) => {
    [...row.cells].forEach((cell, j) => {
        cell.innerHTML = oObjects[i][j];
    });
  });
}

Solution 2:

push tr rows into array or object and sort by your custom sort function: https://jsfiddle.net/2dq7m8k9/

you are using jquery so life is good :)

functionSortByTotal(tr1, tr2){//descending sortingvar total1 = parseInt(tr1.find('td:last-child').text());
       var total2 = parseInt(tr2.find('td:last-child').text());
       return ((total1 > total2) ? -1 : ((total1 < total2) ? 1 : 0));
   }

   var trs=newArray();
   $('#mytable tbody').first().children('tr').each(function(){
    trs.push($(this).clone());     
   });
   trs.sort(SortByTotal);
   $('#mytable tbody').first().empty();  
   var i=0;
   for (i = 0; i < trs.length; i++) {
      $('#mytable tbody').first().append(trs[i]); 
   }

Post a Comment for "How To Sort The Table To Order By Points At End Of Column Using Javascript"