How can I implement a simple JavaScript sort table solution? I just need to sort each column alphabetically.
It doesn’t need to handle numbers or special formats like currency—just a click on the column header to toggle between sorting A-Z and Z-A. Does anyone have a straightforward solution for this?
You can grab the table rows and sort them using JavaScript’s native sort() function, which works well for alphabetical sorting.
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchCount = 0;
table = document.getElementById("myTable");
switching = true;
dir = "asc"; // Initial direction
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
if (dir === "asc" && x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
} else if (dir === "desc" && x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
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;
}
}
}
}
You can attach this function to your table header with an onclick event.
Another way is to use data-* attributes to store sorting directions and toggle between ascending and descending orders.
function sortTable(n) {
var table = document.getElementById("myTable");
var rows = Array.prototype.slice.call(table.rows, 1); // Exclude header row
var th = table.getElementsByTagName("TH")[n];
var asc = th.getAttribute('data-sort') !== 'asc';
rows.sort(function(a, b) {
var x = a.cells[n].innerText.toLowerCase();
var y = b.cells[n].innerText.toLowerCase();
return asc ? x.localeCompare(y) : y.localeCompare(x);
});
th.setAttribute('data-sort', asc ? 'asc' : 'desc');
for (var i = 0; i < rows.length; i++) {
table.appendChild(rows[i]); // Reappend rows in sorted order
}
}
This method uses the localeCompare() method to sort strings and handles the sorting toggle with data-sort attributes.