JSFiddle - React, Tailwind, and code Playground

by saurabh97

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="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;
}
.A_1, .A_2, .B_1{
padding-left: 30px;
}

JavaScript

var arr = [
    {
        f_name: 'George',
         age: 279,
        groupType:'A'
    },
    {
        f_name: 'George_child_a',
         age: 202,
        groupType:'A_1'
    },
    {
        f_name: 'George_child_b',
         age: 50,
        groupType:'A_2'
    },{
        f_name: 'Joe',
         age: 12,
        groupType:'B'
    },
    {
        f_name: 'Joe_child_a',
         age: 22,
        groupType:'B_1'
    },
    {
        f_name: 'Hilary',
         age: 44,
        groupType:'C'
    }
];

$(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();
}


 sortResults("f_name", true);

function renderResults () {
    var html = '';
    for (var e in arr) {
        html += '<tr>'
            +'<td class='+arr[e].groupType+'>'+arr[e].f_name+'</td>'
             
            +'<td class='+arr[e].groupType+'>'+arr[e].age+'</td>'
        +'</tr>';
    }
    $('#results').html(html);
}