1

I am trying to sort an array at click by date day / month / year (increasing and decreasing) using Jquery. However, the table is not correctly sorted when I click on on the button Date.

Here is my script: https://jsfiddle.net/mr8vnj57/9/

var compare = {                           // Declare compare object
  name: function(a, b) {                  // Add a method called name
    a = a.rep
    lace(/^the /i, '');          // Remove The from start of parameter
    b = b.replace(/^the /i, '');          // Remove The from start of parameter

    if (a < b) {                          // If value a is less than value b
      return -1;                          // Return -1
    } else {                              // Otherwise
      return a > b ? 1 : 0;               // If a is greater than b return 1 OR
    }                                     // if they are the same return 0
  },
  duration: function(a, b) {              // Add a method called duration
    a = a.split(':');                     // Split the time at the colon
    b = b.split(':');                     // Split the time at the colon

    a = Number(a[0]) * 60 + Number(a[1]); // Convert the time to seconds
    b = Number(b[0]) * 60 + Number(b[1]); // Convert the time to seconds

    return a - b;                         // Return a minus b
  },
  date: function(a, b) {                  // Add a method called date
    a = new Date(a);                      // New Date object to hold the date
    b = new Date(b);                      // New Date object to hold the date

    return a - b;                         // Return a minus b
  }
};

$('.sortable').each(function() {
  var $table = $(this);                     // This sortable table
  var $tbody = $table.find('tbody');        // Store table body
  var $controls = $table.find('th');        // Store table headers
  var rows = $tbody.find('tr').toArray();   // Store array containing rows

  $controls.on('click', function() {        // When user clicks on a header
    var $header = $(this);                  // Get the header
    var order = $header.data('sort');       // Get value of data-sort attribute
    var column;                             // Declare variable called column

    // If selected item has ascending or descending class, reverse contents
    if ($header.is('.ascending') || $header.is('.descending')) {  
      $header.toggleClass('ascending descending');    // Toggle to other class
      $tbody.append(rows.reverse());                // Reverse the array
    } else {                                        // Otherwise perform a sort                            
      $header.addClass('ascending');                // Add class to header
      // Remove asc or desc from all other headers
      $header.siblings().removeClass('ascending descending'); 
      if (compare.hasOwnProperty(order)) {  // If compare object has method
        column = $controls.index(this);         // Search for column’s index no

        rows.sort(function(a, b) {               // Call sort() on rows array
          a = $(a).find('td').eq(column).text(); // Get text of column in row a
          b = $(b).find('td').eq(column).text(); // Get text of column in row b
          return compare[order](a, b);           // Call compare method
        });

        $tbody.append(rows);
      }
    }
  });
});
td {
 background-color: #fff;}
table.sortable th:hover {
 cursor: pointer;}
th.ascending, th.descending, table.sortable th:hover {
 background-color: #00cccc;
 color: #fff;}

/* Arrows for table sorting */
th.ascending:after {
 font-size: 60%;
    content: '\25B2';
    float: left;
 padding: 4px 5px 0px 0px;}
th.descending:after {
 font-size: 60%;
    content: '\25BC';
    float: left;
 padding: 4px 5px 0px 0px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="sortable">
      <thead>
        <tr>
          <th >Date</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>16-07-2014</td>
        </tr>
        <tr>
          <td>28-02-2014</td>
        </tr>
        <tr>
          <td>10-04-2012</td>
        </tr>
        
         <tr>
          <td>10-04-2016</td>
        </tr>
 
      </tbody>
    </table>

That tells me

Date decreasing : 10-04-2016 10-04-2012 28-02-2014 16-07-2014

Date increasing : 16-07-2014 28-02-2014 10-04-2012 10-04-2016

Do you have another solution or can you correct me the script.

Thank you for your help.

d621
  • 35
  • 1
  • 5
  • The first line of your compare.name method has a new line breaking up the `replace` method call. – Taplar Jun 27 '18 at 20:49
  • 1
    Read the answers to [Converting a string to a date in JavaScript](https://stackoverflow.com/q/5619202) and/or [Why does Date.parse give incorrect results?](https://stackoverflow.com/q/2587345). Running `new Date()` on strings in that format most likely won't parse correctly. – Heretic Monkey Jun 27 '18 at 20:51
  • it seems to be ordering them not by date value but by the index of the table cell...that's what you need to fix.. sort by cell value... – Rachel Gallen Jun 27 '18 at 23:27
  • i am very confused with the usage of compare. compare is an object and yet you are calling it as a function? how is that possible. you declared several properties in compare object but they are never utilized. – Nguai al Dec 29 '19 at 01:29

1 Answers1

0

There are two issues:

  • The code is looking in the header cell for a data-sort attribute. None is found, so the sort isn't using the date function as expected.
  • The date format is "DD-MM-YYYY". Using new Date() requires a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601; copied from MDN dateString parameter). I opted to use the new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]); format.

== Updated demo ==

To fix the above issues, add the data-sort attribute:

<th data-sort="date">Date</th>

And modify the compare.date function as follows:

date: function(a, b) {                  // Add a method called date
  a = a.split('-');
  b = b.split('-');
  a = new Date(a[2], a[1] - 1, a[0]);   // New Date object to hold the date
  b = new Date(b[2], b[1] - 1, b[0]);   // New Date object to hold the date
  return a - b;                         // Return a minus b
}
Community
  • 1
  • 1
Mottie
  • 84,355
  • 30
  • 126
  • 241