What are the javascript sorting tables?
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>
Name
Surname
Age
Raja
Dey
18
Mamata
Sharma
20
Avijit
Sharma
21
Sharanya
Dutta
26
Nabin
Roy
27
</body>
</html>
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] = "">