JSFiddle - React, Tailwind, and code Playground
HTML
Click on the table headings to sort the results.
<table>
<thead id="headings">
<tr>
<th data-attr="f_name">First Name</th>
<th data-attr="l_name">Last Name</th>
<th data-attr="age">Age</th>
</tr>
</thead>
<tbody id="results">
<!-- this will be auto-populated -->
</tbody>
</table>
CSS
table {
margin: 3px;
}
table th {
font-weight: bold;
cursor: pointer;
}
table th, table td {
padding: 3px;
border: 1px solid #000;
}
JavaScript
var arr = [
{
f_name: 'George',
l_name: 'Washington',
age: 279
},
{
f_name: 'Abraham',
l_name: 'Lincoln',
age: 202
},
{
f_name: 'Barack',
l_name: 'Obama',
age: 50
}
];
$(function() {
$('#headings th').on('click', function() {
var attr = $(this).attr('data-attr');
var asc = (!$(this).attr('data-asc')); // switch the order, true if not set
// clear any previous sort order indicators
$('#headings th').each(function() {
$(this).removeAttr('data-asc');
});
// set sort order indicator
if (asc) {
$(this).attr('data-asc', 'asc');
}
sortResults(attr, asc);
});
renderResults();
});
function sortResults(prop, asc) {
arr.sort(function(a, b) {
if (asc) {
return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
} else {
return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
}
});
renderResults();
}
function renderResults () {
var html = '';
for (var e in arr) {
html += '<tr>'
+'<td>'+arr[e].f_name+'</td>'
+'<td>'+arr[e].l_name+'</td>'
+'<td>'+arr[e].age+'</td>'
+'</tr>';
}
$('#results').html(html);
}