JSFiddle - React, Tailwind, and code Playground

by Gabriele Petrioli

HTML

<div id="menu">
    <button id="byName" class="active">Player Name</button>
    <button id="byCountry">Country</button>
    <button id="byScore">Score</button>
</div>
<div id="list"></div>

JavaScript

$(document).ready(function () {
    var data;
    $.post("/echo/json/",{'json':'{"player": [{"name": "John","country": "USA","score": 102400}, {"name": "Mary","country": "Australia","score": 80001}, {"name": "Jane","country": "England", "score": 103900},{"name": "Logan","country": "Chile","score": 1020},{"name": "Cara","country": "Canada","score": 10400}]}'}, function (json) {
        data = json;
        setup(data);
    });
});

function setup(data){
    displayData(data.player);

    $("#byName").click(function () {
        var sorted = data.player.sort(byName);
        displayData(sorted);
    });
    $("#byCountry").click(function () {
        var sorted = data.player.sort(byCountry);
        displayData(sorted);
    });
    $("#byScore").click(function () {
        var sorted = data.player.sort(byScore);
        displayData(sorted);
    });
}

function displayData(array) {
    var list = $("#list").empty();
    $.each(array, function () {
       list.append("<div class='player'><ul><li>" + this['name'] + "</li><li>" + this['country'] + "</li><li>" + this['score'] + "</li></ul></div>");
    });
}

function byCountry(a, b) {
    if (a.country < b.country) return -1;
    if (a.country > b.country) return 1;
    return 0;
};
function byName(a, b) {
    if (a.name < b.name) return -1;
    if (a.name > b.name) return 1;
    return 0;
};
function byScore(a, b) {
    if (a.score < b.score) return -1;
    if (a.score > b.score) return 1;
    return 0;
};