Trax Trax - 4 months ago 18
jQuery Question

Sort table by column value before display jquery/js

I was wondering if it's possible to sort the final table content, before inserting it into the html, by the value of the paying column. The code generating the table is the following

function populateJobMarket() {
var tableContent = '';
$.getJSON('modalRoutes/jobmarket', function(data){
$.each(data, function() {
var cName = this.companyName;
$.each(this.hiring, function(){
tableContent += '<tr class=\'target_row\'>';
tableContent += '<td>' + cName + '</td>';
tableContent += '<td>' + this.paying + '</td>';
tableContent += '<td> <button type=\'button\' class=\'btn btn-warning job_apply\' id=' + this._id + '> Apply </button></td>';
tableContent += '</tr>';
});
});
$('#jobMarket_pp #joblist table tbody').html(tableContent); // Sort it before this step
});

}


HTML Code:

<div class="modal fade" id="jobMarket_pp" tabindex="-1" role="dialog" aria-labelledby="jobMarket_pp">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title" id="jobMarket_content" Job Offers</h4> </div> <div class="modal-body"> <div class='jobMarketAlert'></div>
<div id="joblist">
<table>
<thead>
<th>Company Name</th>
<th>Salary</th>
<th>Work</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Answer

You'll first need to flatten the data:

var new_data = [];

$.each(data, function() {
  var companyName = this.companyName;
  $(this.hiring).each(function(index, hire){
    hire.companyName = companyName;
    new_data.push(hire);
  });
});

Then sort the new flattened data by paying:

new_data.sort(function(a, b) {
    return a.paying < b.paying;
});

Now iterate over the data:

$.each($(new_data), function(){
  tableContent += '<tr class=\'target_row\'>';
  tableContent += '<td>' + this.companyName + '</td>';
  tableContent += '<td>' + this.paying + '</td>';
  tableContent += '<td> <button type=\'button\' class=\'btn btn-warning job_apply\' id=' + this._id + '> Apply </button></td>';
  tableContent += '</tr>'
});

I also recommend using, instead:

$(new_data).each(function(hire)) {
  tableContent += '<tr class=\'target_row\'>';
  tableContent += '<td>' + hire.companyName + '</td>';
  tableContent += '<td>' + hire.paying + '</td>';
  tableContent += '<td> <button type=\'button\' class=\'btn btn-warning job_apply\' id=' + hire._id + '> Apply </button></td>';
  tableContent += '</tr>'
});

Using this is JavaScript often leads to headaches, as it doesn't behave like this in other languages.