jensej2 jensej2 - 1 year ago 88
Javascript Question

Received data from socket and sort and display

I received data from socket and I need to live sort this data and display.
My code looke like this but only display unsort data.

$.each( data.players, function( key, value ) {
var p = value.value[0]/1000;
$('<tr>'+
'<td>'+
'<p class="price">$'+ p.toFixed(2)+'</p>'+
'</td>'+
'</tr>').appendTo('#target').hide().fadeIn(700);
});


Second problem:
When data was sorted and displayed and socket receive new player, it shoud be added on right place.

Data to sort (each object with id have price atrubute):
data to sort

Answer Source

Try the following

var data = {
  4: {},
  76: {}
};

// simulate async data retrieval from socket 
setInterval(function(){
  // random data
  data[getRandom(1, 10000)] = {};
  
  // update dome when new data is received
  updateDom();
}, getRandom(1000, 5000));

// call this method each time new data is received
updateDom();

function updateDom() {
  var keys = [];

  // add object keys to an array to be able to sort them
  for (k in data) {
    if (data.hasOwnProperty(k)) {
      keys.push(parseInt(k));
    }
  }

  var dom = '';
  keys.sort(function(a, b) {
    // sort values
    return (a < b) ? -1 : ((a > b) ? 1 : 0);
  }).forEach(function(e) {
    // for each element in the array generate dom
    dom = dom + '<tr><td>' +
      '<p class="price">$' + e + '</p>' +
      '</td></tr>';
  });

  // set dom in target
  $('#target')
    .hide()
    .html(dom)
    .fadeIn(700);
}

// utils - ignore for real implementation
function getRandom(min, max) {
    return Math.random() * (max - min) + min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target">Data here!</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download