JSFiddle - React, Tailwind, and code Playground
HTML
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Sex</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Alex</td>
<td>Kane</td>
<td>m</td>
</tr>
<tr>
<td>2</td>
<td>Lucy</td>
<td>Smith</td>
<td>f</td>
</tr>
<tr>
<td>3</td>
<td>Jane</td>
<td>Doe</td>
<td>f</td>
</tr>
<tr>
<td>4</td>
<td>Lois</td>
<td>Chang</td>
<td>f</td>
</tr>
<tr>
<td>5</td>
<td>Zack</td>
<td>Robbs</td>
<td>m</td>
</tr>
</tbody>
</table>
CSS
table,
th,
td {
border: 1px solid black;
}
th {
cursor: pointer;
background-color: lightgray;
}
JavaScript
$('th').click(function() {
var table = $(this).parents('table').eq(0)
// We evaluate asc before calling the comparer.
this.asc = !this.asc;
// We call the comparer whith an additional parameter which specifies the sort order.
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index(), !this.asc))
for (var i = 0; i < rows.length; i++) {
table.append(rows[i])
}
})
function comparer(index, desc) {
return function(a, b) {
var valA = getCellValue(a, index),
valB = getCellValue(b, index)
var result = $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB);
// If desc is set we sort descending otherwise ascending by default.
if (desc) {
result *= -1;
}
return result;
}
}
function getCellValue(row, index) {
return $(row).children('td').eq(index).text()
}