简体   繁体   中英

Table sort by total column in JavaScript

I am trying to sort the table by total value. Link . This works but it fails when two table elements have same point.

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. Each row is dynamically created as well.

Please help

 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]; }); }); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onClick="sortTotal()"> Sort</button> </button> <table class="fl-table"> <thead> <tr> <th>Player</th> <th>Player Name</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/70C/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/70C/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/70C/O https://placeholder.com/"></td> <td>Latheesh VM V</td> <td>2</td> <td>26</td> <td>4</td> </tr> </tbody> </table>

You are sorting by wrong column. a[a.length -2] > b[b.length -2] should be a[a.length -1] > b[b.length -1] and sort will make 25, 4, 4 by total

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM