If you insist on using the linked example, see this part:
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
}
It's working with innerHTML, which is always a string, so the comparison operators performs comparison of strings (where "11" < "2"). To make it compare numeric content as actual numbers, you must first convert it to numbers (if the content is not a number, parseFloat results in a NaN
object, which is checked for by the isNaN()
function):
var xNumeric = parseFloat(x.innerHTML);
var yNumeric = parseFloat(y.innerHTML);
if (dir == "asc") {
if (!isNaN(xNumeric) && !isNaN(yNumeric) && xNumeric > yNumeric
|| (isNaN(xNumeric) || isNaN(yNumeric)) && x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
} else if (dir == "desc") {
if (!isNaN(xNumeric) && !isNaN(yNumeric) && xNumeric < yNumeric
|| (isNaN(xNumeric) || isNaN(yNumeric)) && x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
}
Which translates as "if the compared contents are numeric, compare their numeric values OR if one of them is not, compare them as strings".
Approach to compare dates would be the same - you'd first converted the content to a date object (roughly var xDate = new Date(x.innerHTML);
, which is not exhaustive though) and compared the date objects; checking if a variable is a valid date object is a bit harder hough, check this or that SO questions.