JSFiddle - React, Tailwind, and code Playground
by brigand
HTML
<table id="results-table">
<thead>
<tr>
<th onclick="sortTable(0)">test</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
</tbody>
</table>
JavaScript
window.onload = function() {
window.tableSorts = [1];
};
function sortTable(sortColumn) {
var ascDescVal = window.tableSorts[sortColumn];
var table = document.getElementById("results-table");
const tableBody = table.querySelector('tbody');
const tableData = table2data(tableBody);
console.log(tableData)
tableData.sort((a, b) => {
if (isNaN(a[sortColumn])) {
if(a[sortColumn] > b[sortColumn]){
return ascDescVal;
}
return -1* ascDescVal;
} else {
if(Number(a[sortColumn]) > Number(b[sortColumn])){
return ascDescVal;
}
return -1 * ascDescVal;
}
});
data2table(tableBody, tableData);
if (window.tableSorts[sortColumn] == 1) {
window.tableSorts[sortColumn] = -1;
} else {
window.tableSorts[sortColumn] = 1;
}
}
function table2data(tableBody) {
const tableData = [];
tableBody.querySelectorAll('tbody tr')
.forEach(row => {
const rowData = [];
row.querySelectorAll('td')
.forEach(cell=>{
rowData.push(cell.innerText);
})
tableData.push(rowData);
});
return tableData;
}
function data2table(tableBody, tableData) {
tableBody.querySelectorAll('tr')
.forEach((row, i) => {
const rowData = tableData[i];
row.querySelectorAll('td')
.forEach((cell, j) => {
cell.innerText = rowData[j];
})
tableData.push(rowData);
});
}