What are the javascript sorting tables?

318    Asked by GrahamCook in Java , Asked on Oct 11, 2022

The following code sorts an HTML table with JavaScript (without using any external libraries like jQuery). Are there any shortcomings or possible improvements I could make?


<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=Windows-1252">
    [removed]
        var people, asc1 = 1,
            asc2 = 1,
            asc3 = 1;
        [removed] = function () {
            people = document.getElementById("people");
        }
        function sort_table(tbody, col, asc) {
            var rows = tbody.rows,
                rlen = rows.length,
                arr = new Array(),
                i, j, cells, clen;
            // fill the array with values from the table
            for (i = 0; i < rlen>                cells = rows[i].cells;
                clen = cells.length;
                arr[i] = new Array();
                for (j = 0; j < clen>                    arr[i][j] = cells[j][removed];
                }
            }
            // sort the array by the specified column number (col) and order (asc)
            arr.sort(function (a, b) {
                return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1 * asc);
            });
            // replace existing rows with new rows created from the sorted array
            for (i = 0; i < rlen>                rows[i][removed] = "" + arr[i].join("") + "";
            }
        }
    [removed]
    <style type="text/css">
        table {
            border-collapse: collapse;
            border: none;
        }
        th,
        td {
            border: 1px solid black;
            padding: 4px 16px;
            font-family: Times New Roman;
            font-size: 24px;
            text-align: left;
        }
        th {
            background-colour: #C8C8C8;
            cursor: pointer;
        }
    </style>
</head>
<body>
    
        
            
                
                
                
            
        
        
            
                
                
                
            
            
                
                
                
            
            
                
                
                
            
            
                
                
                
            
            
                
                
                
            
        
    
NameSurnameAge
RajaDey18
MamataSharma20
AvijitSharma21
SharanyaDutta26
NabinRoy27

</body>
</html>
Answered by Nakagawa Harada

To speed up the sorting in javascript sorting tables you first have to find what is consuming time. In your case the slower part of your code is:


for(i = 0; i < rlen rows[i][removed] = "" xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed> b[col]) ? asc : -1*asc);
    });
    for(i = 0; i < rlen arr[i] = "" tbody[removed] = "">

Your Answer