简体   繁体   English

按子字符串排序表

[英]Sort table by sub-string

I'm trying to sort a table by course number, but I need to use a substring to sort by number. 我正在尝试按课程编号对表格进行排序,但是我需要使用子字符串按编号对表格进行排序。 The course name looks like CX-001 for example, I wanting to ignore the first three characters. 课程名称看起来像CX-001,例如,我想忽略前三个字符。 I'm using Vanilla Javascript. 我正在使用Vanilla Javascript。 I'm not sure where to apply the substring, but I know I got it wrong. 我不确定在哪里应用子字符串,但是我知道我弄错了。

 function sortSubNum(subNum) { var switchcount = 0; var table = document.getElementById("myTable2").substring(2); var switching = true; // Set the sorting direction to ascending: var dir = "asc"; /* Make a loop that will continue until no switching has been done: */ while (switching) { switching = false; var rows = table.rows; var shouldSwitch; for (var i = 1; i < (rows.length - 1); i++) { var x = rows[i].getElementsByTagName("TD")[subNum]; var y = rows[i + 1].getElementsByTagName("TD")[subNum]; //var resX = x.substring(2); //var resY = y.substring(2); if (dir === "asc") { if (Number(x.textContent.substring(2)) < Number(y.textContent.substring(2))) { //if so, mark as a switch and break the loop: shouldSwitch = true; break; } } else if (dir === "desc") { if (Number(x.textContent.substring(2)) > Number(y.textContent.substring(2))) { shouldSwitch = true; break; } } } if (shouldSwitch) { rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); switching = true; switchcount++; } else { if (switchcount === 0 && dir === "asc") { dir = "desc"; switching = true; } } } } sortSubNum(1); 
 <table id="myTable2"> <thead> <tr> <th>Teacher</th> <th>Course Number</th> </tr> </thead> <tbody> <tr> <td>Smith</td> <td>CS-301</td> </tr> <tr> <td>Kelly</td> <td>CX-201</td> </tr> <tr> <td>Park</td> <td>CS-001</td> </tr> </tbody> </table> 

Although you already found problem in your code but my solution is based on @Patrick Roberts suggestion given in comment. 尽管您已经在代码中发现问题,但是我的解决方案基于@Patrick Roberts在注释中提出的建议。

Instead of implementing your own sorting method directly on the DOM, consider initializing an Array of elements and calling Array.prototype.sort(), then reinserting the newly ordered elements back into the table. 与其直接在DOM上直接实现自己的排序方法,不如考虑初始化一个元素数组并调用Array.prototype.sort(),然后将新排序的元素重新插入表中。 It would be a lot faster and less error-prone 这样会更快,更不会出错

 function sortTable(tbody, col, asc){ var rows = tbody.rows; var rowsLen = tbody.rows.length; var arr = new Array(); var i, j, cells, cellLen; // fill the array with values from the table for(i = 0; i < rowsLen; i++){ cells = rows[i].cells; cellLen = cells.length; arr[i] = new Array(); for(j = 0; j < cellLen; j++){ arr[i][j] = cells[j].innerHTML; } } //short the array arr.sort(function(a, b){ //this is your use case.sort the data in array after spilt. var aCol=a[col].split("-")[1]; var bCol=b[col].split("-")[1]; return (aCol == bCol) ? 0 : ((aCol > bCol) ? asc : -1*asc); }); for(i = 0; i < rowsLen; i++){ arr[i] = "<td>"+arr[i].join("</td><td>")+"</td>"; } tbody.innerHTML = "<tr>"+arr.join("</tr><tr>")+"</tr>"; } var tbody=document.getElementById("myTable2Tbody"); sortTable(tbody,1, 1); //for asc use 1,for dsc use -1 
 <table id ="myTable2"> <thead> <tr> <th>Teacher</th> <th>Course Number</th> </tr> </thead> <tbody id ="myTable2Tbody"> <tr> <td>Smith</td> <td>CS-301</td> </tr> <tr> <td>Kelly</td> <td>CX-201</td> </tr> <tr> <td>Park</td> <td>CS-001</td> </tr> </tbody> </table> 

Check out this solution using Array.sort 使用Array.sort查看此解决方案

 var tbody = document.querySelector('#myTable2 tbody') var trs = tbody.querySelectorAll('tr') var sorted = [...trs].sort((tra, trb) => { var courseA = tra.querySelectorAll('td')[1].innerText var courseB = trb.querySelectorAll('td')[1].innerText return courseA.split('-')[1] - courseB.split('-')[1] }) tbody.innerHTML = ''; sorted.forEach(tr => tbody.appendChild(tr)) 
 <table id="myTable2"> <thead> <tr> <th>Teacher</th> <th>Course Number</th> </tr> </thead> <tbody> <tr> <td>Smith</td> <td>CS-301</td> </tr> <tr> <td>Kelly</td> <td>CX-201</td> </tr> <tr> <td>Park</td> <td>CS-001</td> </tr> </tbody> </table> 

Removed substring from var table. 从var表中删除了子字符串。 Also, I changed conditionals in the for loop from 另外,我从

if (Number(x.textContent.substring(2)) < Number(y.textContent.substring(2)))

to

if(x.textContent.substring(2) < y.textContent.substring(2))

function sortSubNum(subNum) {
    var switchcount = 0;

    var table = document.getElementById("myTable2");
    var switching = true;
    // Set the sorting direction to ascending:
    var dir = "asc"; 
    /* Make a loop that will continue until
    no switching has been done: */
    while(switching){
        switching = false;
        var rows = table.rows;
        var shouldSwitch;
        for(var i = 1; i < (rows.length - 1); i ++){

            var x = rows[i].getElementsByTagName("TD")[subNum];
            var y = rows[i + 1].getElementsByTagName("TD")[subNum];
            //var resX = x.substring(2);
            //var resY = y.substring(2);

            if(dir === "asc"){
                if(x.textContent.substring(2) < y.textContent.substring(2)) {
                    //if so, mark as a switch and break the loop:
                    shouldSwitch = true;
                    break;
                }
            }else if(dir === "desc"){
                if(x.textContent.substring(2) > y.textContent.substring(2)){
                    shouldSwitch = true;
                    break;
                }
            }
        }
        if(shouldSwitch){
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            switching = true;
            switchcount++;
        }else{
            if (switchcount === 0 && dir === "asc") {
                dir = "desc";
                switching = true;
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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