Jquery sort of table -> Numbers before text

Viewed 108

I am working on a wait times API to show the current queuing times of the Disney-parks. The wait times are loaded in a table in alphabetical order.

Now I have used the following code to sort this table on highest waits on top of the table to the lowest waits. That is what I want:

$(document).ready(function(){
var sorted = $('#mytable tbody tr').sort(function(b, a) {
  var a = $(a).find('td:last').text(), b = $(b).find('td:last').text();
  return a.localeCompare(b, false, {numeric: true})
})

$('#mytable tbody').html(sorted)
});

This works great, BUT as you can see in the image below the text values like 'Closed' and 'Refurbishment' are on top of the table, above the highest wait time.

How can I change this order of the table to get the highest wait times on top of the table and at last the text-values?

Current order, want to change this

So I want to get:

20 min.
15 min.
5 min.
Open
Closed
Refurbishment
1 Answers

To sort as you require, you need to sort differently dependent on whether the value is numeric or not. If both are numeric, compare as you currently do. Otherwise, if only one is numeric, sort that to the beginning; and if both are not numeric, sort according to your required order (Open, Closed, Refurbishment), which can be implemented by looking up the phrase in an object that defines the sort order:

var states = {
  'Open': 0,
  'Closed': 1,
  'Refurbishment': 2
};

$(document).ready(function() {
  var sorted = $('#mytable tbody tr').sort(function(b, a) {
    var a = $(a).find('td:last').text(),
      b = $(b).find('td:last').text();
    if (!isNaN(parseInt(a))) {
      if (!isNaN(parseInt(b))) {
        // a and b both numeric
        return a.localeCompare(b, false, {
          numeric: true
        });
      } else {
        // a numeric, b not, sort b last
        return 1;
      }
    } else if (!isNaN(parseInt(b))) {
      // a not numeric, b numeric, sort a last
      return -1;
    } else {
      // a not numeric, b not numeric, sort regular
      return states[b] - states[a];
    }
  });
  $('#mytable tbody').html(sorted)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="mytable">
  <tbody>
    <tr>
      <td>Challenge trails</td>
      <td>Refurbishment</td>
    </tr>
    <tr>
      <td>Camp Discovery</td>
      <td>Open</td>
    </tr>
    <tr>
      <td>Soaring</td>
      <td>120 mins</td>
    </tr>
    <tr>
      <td>Fantasia</td>
      <td>20 mins</td>
    </tr>
    <tr>
      <td>Shipwreck Shore</td>
      <td>5 mins</td>
    </tr>
    <tr>
      <td>Rex's Racer</td>
      <td>105 mins</td>
    </tr>
    <tr>
      <td>Slinky Dog</td>
      <td>Closed</td>
    </tr>
  </tbody>
</table>

Related