简体   繁体   中英

How to sort table column as number? (only javascript)

I need to sort this table but Percentage and Numbers columns are sorting in a strange way. It's sorting them as strings, not numbers. I googled a lot and tried to use parseInt, parseFloat and number but the code below is the best I could get.

Any way I could convert only these columns (and not the name column) to numbers?

Sorry if it's too noob of a question, I'm a beginner in coding. :-/

 var tabela, asc1 = 1, asc2 = 1, asc3 = 1; window.onload = function() { tabela = document.getElementById("table"); } function sort_table(tbody,col,asc) { var rows = tbody.rows, rlen = rows.length, arr = new Array(), i, j, cells, clen; for (i=0 ; i<rlen ; i++){ cells = rows[i].cells; clen = cells.length; arr[i] = new Array; for( j=0; j<clen ; j++){ arr[i][j] = cells[j].innerHTML; } } arr.sort( function(a, b){ return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1 * asc); }); for (i=0; i<rlen ; i++){ rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>"; } } 
 <table class="table"> <thead> <th onclick="sort_table(table,0,asc1);asc1 *= -1;asc2 = 1; asc3 = 1;">Number</th> <th onclick="sort_table(table,1,asc2);asc2 *= -1;asc1 = 1; asc3 = 1;">Name</th> <th onclick="sort_table(table,2,asc3);asc3 *= -1;asc1 = 1; asc2 = 1;">Percentage</th> </thead> <tbody id="table"> <tr> <td>1</td> <td>A</td> <td>10%</td> </tr> <tr> <td>5</td> <td>D</td> <td>55%</td> </tr> <tr> <td>3</td> <td>F</td> <td>3%</td> </tr> </tbody> </table> 

var sortVal = cells[j].innerHTML;
arr[i][j] = isNaN(sortVal) ? sortVal : sortVal/1;

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