Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

What are the javascript sorting tables?

Asked by Graham Cook Oct 11, 2022 964 views 1 answer
Share

About this question

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>

Your answer

1 Answer

More Java discussions