How to sort the table to order by points at end of column using javascript

雨燕双飞 提交于 2021-01-07 03:02:09

问题


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 them by total in javascript. Each row is dynamically created as well.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="fl-table">
  <thead>
    <tr>
      <th>Player</th>
      <th>Player Name</th>
      <!-- <th>W1</th>
            <th>W2</th> -->
      <th>W1</th>
      <th>W2</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="agl-profile-img-new"><img src="https://via.placeholder.com/70

C/O https://placeholder.com/"></td>
      <td>Heather Rankin</td>
      <td>4</td>
      <td>21</td>
      <td>25</td>
    </tr>
    <tr>
      <td class="agl-profile-img-new"><img src="https://via.placeholder.com/70

C/O https://placeholder.com/"></td>
      <td>Stephen Puopolo</td>
      <td>3</td>
      <td>1</td>
      <td>4</td>
    </tr>
    <tr>
      <td class="agl-profile-img-new"><img src="https://via.placeholder.com/70

C/O https://placeholder.com/"></td>
      <td>Latheesh V M V</td>
      <td>2</td>
      <td>26</td>
      <td>28</td>
    </tr>
  </tbody>
  <tbody>
  </tbody>
</table>

Is there is any way? Please help


回答1:


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

const sortTotal = () => {
  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];
    });
  });
}



回答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 :)

   function SortByTotal(tr1, tr2){//descending sorting
       var 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=new Array();
   $('#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]); 
   }


来源:https://stackoverflow.com/questions/65388204/how-to-sort-the-table-to-order-by-points-at-end-of-column-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!