0

I could really use a second pair of eyes from someone more versed in Javascript and sorting algorithms.

I'm trying to sort my table by date (mm/dd/yyyy)

This solution is working fantastic for ascending order, even on our larger data tables, but when I switch to the less-than sign for descending order, it works to a certain extent.

Smaller data sets work fine, but larger ones just brick the loop. I'm not sure what the disconnect is here. It is especially confusing, because ascending order works fine.

 WebApp.sortDateReverse = function(colNam, colNum) 
      {
        var table, rows, switching, i, x, y, shouldSwitch;
        table = document.getElementById("myTable");
        switching = true;
        console.log('This is colNum', colNum);
        console.log('This is colName', colNam);
        /*Make a loop that will continue until
        no switching has been done:*/
        while (switching) {
          //start by saying: no switching is done    
          switching = false;
          rows = table.rows;
          /*Loop through all table rows (except the
          first, which contains table headers):*/
          for(i = 1;i<(rows.length - 1);i++) {
            //start by saying there should be no switching:
            shouldSwitch = false;
            console.log('This is i:', i);
            console.log('This is row length:', rows.length);
            /*Get the two elements you want to compare,
            one from current row and one from the next:*/
            x = rows[i].getElementsByTagName("TD")[colNum];
            y = rows[i + 1].getElementsByTagName("TD")[colNum];
            //check if the two rows should switch place:
            if (WebApp.convertDate(x.innerHTML) < WebApp.convertDate(y.innerHTML)) {
              //if so, mark as a switch and break the loop:
              //console.log('Switching x:', x.innerHTML , 'with y:', y.innerHTML);
              shouldSwitch = true;
              break;
            }
          }
          if (shouldSwitch) {
            /*If a switch has been marked, make the switch
            and mark that a switch has been done:*/
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            switching = true;
          }
        }
};

WebApp.convertDate = function(d) {
        return Date.parse(d)
        };

Powermaster Prime
  • 402
  • 1
  • 2
  • 16
  • So you're sorting elements directly in the DOM? Thats rather unusual. Is there not a data model that can be sorted and the DOM re-rendered? If you are wedded to the sorting of DOM elements, I wouldn't attempt a real-time shuffle of all the elements using the DOM as your store. Just grab all of the elements, sort them as an array with `arr.sort(...)` (in-memory) and then dump them back into the DOM in a single operation. – spender Feb 22 '23 at 19:17
  • 2
    Some notes: you want textContent, not innerHTML. Also, if you're sorting, the easiest way to do that is to use the built in `sort` (e.g. `const list = Array.from(table.querySelectorAll("tr")); list.sort((a,b) => { ... });` and then running a forEach after sorting that appends each row to the table (as appending an element that's already in the DOM _moves_ that element instead). – Mike 'Pomax' Kamermans Feb 22 '23 at 19:17
  • I will reevaluate my approach and utilize the `array.sort()` method. I'll come come back with a full rewrite. Hopefully it will help some people. Sometimes I just really need another perspective. – Powermaster Prime Feb 22 '23 at 19:33

1 Answers1

0

Thanks to some help above, I was able to greatly revise this sort into a much cleaner and faster function. Since my data table is already in ascending order, all I had to do was get the elements into an array, and run a reverse() I then run a for loop and add the reverse sorted elements back to the table.

Now it's time to revise my ascending sort function.

      WebApp.sortDateReverse = function() 
      {
        var table, rows, switching, i;
        table = document.getElementById("tableBody");
        const list = Array.from(table.getElementsByTagName("tr"));
        list.reverse();
        rows = table.rows;
        for(i = 0;i<rows.length;i++) {
          table.append(list[i]);
        }
      }
Powermaster Prime
  • 402
  • 1
  • 2
  • 16