Skip to content

Instantly share code, notes, and snippets.

@Luxato
Created November 18, 2020 11:57
Show Gist options
  • Save Luxato/40450882708442f2164a3fbe3efd7018 to your computer and use it in GitHub Desktop.
Save Luxato/40450882708442f2164a3fbe3efd7018 to your computer and use it in GitHub Desktop.
Sort table by arbitrary column with javascript
function sortTable(table, col, reverse) {
var tb = table.tBodies[0],
tr = Array.prototype.slice.call(tb.rows, 0),
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) {
return reverse
* (a.cells[col].textContent.trim()
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]);
}
// Call the function
sortTable(document.getElementById('statisticsTable'), 3, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment