// HTML Table Sorting
let sortDirection = {}; // Keep track of the sort direction for each column
function sortTableByColumn(columnIndex, type) {
const table = document.getElementById("sortableTable");
let rows, switching, i, x, y, shouldSwitch;
switching = true;
// Set the sorting direction to ascending or flip it if already sorting this column
let direction = sortDirection[columnIndex] === "asc" ? "desc" : "asc";
sortDirection[columnIndex] = direction; // Store the new direction
while (switching) {
switching = false;
rows = table.rows;
// Loop through all table rows (except the first, which contains table headers):
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
// Get the two elements you want to compare, one from current row and one from the next:
x = rows[i].getElementsByTagName("TD")[columnIndex];
y = rows[i + 1].getElementsByTagName("TD")[columnIndex];
let xContent = x.innerHTML.toLowerCase();
let yContent = y.innerHTML.toLowerCase();
// Type conversion for numeric sort
if (type === 'number') {
xContent = parseFloat(xContent) || 0;
yContent = parseFloat(yContent) || 0;
}
// Check if the two rows should switch place:
if (direction === "asc") {
if (xContent > yContent) {
shouldSwitch = true;
break;
}
} else if (direction === "desc") {
if (xContent < yContent) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
// If a switch has been marked, make the switch and mark that a switch is done:
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}