I'm trying to make a HTML table sorting system in JavaScript. All I want is to sort each column by clicking on it, but I think I have to use regex to do so. You see, I want to sort numbers (0-9) first, then sort it alphabetically (a-z) then everything else (special characters) and last empty cells.
This is the order it has to go.
1
03
5
data
data1
-data
-data1
*empty cells*
*empty cells*
The code underneath can only sort the empty cells to the bottom (Code currently taken from Sorting HTML table with JavaScript):
var getCellValue = function(tr, idx) {
return tr.children[idx].innerText || tr.children[idx].textContent;
}
var comparer = function(idx, asc) {
return function(a, b) {
return function(v1, v2) {
if (v1 == "")
return 1;
if (v2 == "")
return -1;
return v1 != "" && v2 != "" && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2);
}(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
}
};
Array.prototype.slice.call(document.querySelectorAll("th.sortable")).forEach(function(th) {
th.addEventListener("click", function() {
var table = th.parentNode
var tbody = document.querySelector("tbody")
while (table.tagName.toUpperCase() != "TABLE") table = table.parentNode;
Array.prototype.slice.call(tbody.querySelectorAll("tr"))
.sort(comparer(Array.prototype.slice.call(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(function(tr) {
tbody.appendChild(tr)
});
})
});
Does anyone know a simple solution to my problem?