0

I'm getting desired results, but need to order them alphabetically. I am unsure what to put in exactly in the code:

function showClients(data) {
    var html = '';
    for (var clientId in data) {
        html += '<p>' + clientId;
        html += data[clientId].connected ? ' connected' : ' disconnected';
        html += '</p>';
    }
    if (!html) {
        html += '<p>No clients connected</p>';
    }
    $('#connected_clients').html(html);
}
Nikolay Fominyh
  • 8,946
  • 8
  • 66
  • 102
Doc Falken
  • 229
  • 2
  • 3
  • 8

2 Answers2

1

If I've got the layout of the data structure right, it is a key/value object, which in turn contains objects that have information such as connected.

In that case you can use Object.keys to get the keys first, sort those Object.keys(data).sort(), and create the html from there. For example:

function showClients(data) {
    var html = Object.keys(data).sort().reduce(function(h, clientId){
        return h + '<p>' + clientId
        + (data[clientId].connected ? ' connected' : ' disconnected')
        + '</p>';
    }, '')
        || '<p>No clients connected</p>';

    $('#connected_clients').html(html);
}

function showClients(data) {
    var html = Object.keys(data).sort().reduce(function(h, clientId){
     return h + '<p>' + clientId
        + (data[clientId].connected ? ' connected' : ' disconnected')
        + '</p>';
    }, '')
     || '<p>No clients connected</p>';
    
    $('#connected_clients').html(html);
}


showClients({Client3:{connected:true},Client1:{connected:true},Client2:{connected:false}});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=connected_clients></div>
Me.Name
  • 12,259
  • 3
  • 31
  • 48
0

Call sort on the data like Array.prototype.sort(data). If you don't pass a compare function, it will sort the elements alphabetically.

function showClients(data) {
    var html = '';
    for (var clientId in Array.prototype.sort.call(data)) {
        html += '<p>' + clientId;
        html += data[clientId].connected ? ' connected' : ' disconnected';
        html += '</p>';
    }
    if (!html) {
        html += '<p>No clients connected</p>';
    }
    $('#connected_clients').html(html);
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112