2

I have the following Javascript function from w3schools to sort a column:

function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("myTable");
  switching = true;
  //Set the sorting direction to ascending:
  dir = "asc"; 
  /*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.getElementsByTagName("TR");
    /*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;
      /*Get the two elements you want to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      /*check if the two rows should switch place,
      based on the direction, asc or desc:*/
      if (dir == "asc") {
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          //if so, mark as a switch and break the loop:
          shouldSwitch= true;
          break;
        }
      } else if (dir == "desc") {
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          //if so, mark as a switch and break the loop:
          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;
    //Each time a switch is done, increase this count by 1:
    switchcount ++;      
    } else {
      /*If no switching has been done AND the direction is "asc",
      set the direction to "desc" and run the while loop again.*/
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}

However it doesn't work well on my column called Internet Explorer Version.

It works well with other columns of my table. I don't know why this is happening. Can someone just tell me what's going wrong?

I copied these values on an excel sheet and tried to sort it, but it doesn't sort properly as well. Is it an issue with the values?

It is just taking the first digit of the number into consideration and then sorting. How can I fix this?

5
  • @sauntimo could you please help? Commented Jul 21, 2017 at 15:12
  • post your table Commented Jul 21, 2017 at 15:16
  • not picture but html code Commented Jul 21, 2017 at 15:18
  • document.write() writes over everything. Do not use it. Since you are parsing string into HTML, use innerHTML or even better insertAdjacentHTML() Commented Jul 21, 2017 at 15:54
  • 1
    Welcome to Stack Overflow! Please do not vandalise your posts. Once you have submitted a post, you have licensed the content to the Stack Overflow community at large (under the CC-by-SA license). If you would like to disassociate this post from your account, see What is the proper route for a disassociation request? Commented Jul 21, 2017 at 21:17

2 Answers 2

2

The result is correct as per string operation comparison rule, but your requirement is different.

How string comparison happen ? A < B

  1. It compare UTF-16 value from first digit of both string if it is equal then compare next character.

  2. If character of A's string at some point less than B then A String will be smaller.

  3. If any of string will end before reaching conclusion It will be consider as small string.

for example

  1. "10.0.9200.17609" < "11.0.15063.0" = true because on 2nd digit 0 < 1
  2. "9" < "101" = false because UTF-16 value of '9' is greater than '1'
  3. "101" < "1011" = true because till 3 char both are equal and first string ends So It is smaller.

For your problem you need to split your numbers on .(dot) for example "10.0.9200.17609" after split [10, 0, 9200, 17609] then you need to use following comparator function to decide which element is smaller in your sort algorithm.

/** 
  A and B will be array and element are integer
  return true if A < B else false
**/
function comparator(A, B) {
   var a_length = A.length, b_length = B.length;
   var loop_count = min(a_length, b_length);
   for(var i = 0; i < loop_count; i++) {
     if(A[i] < B[i])
        return true;
     else if (A[i] > B[i])
        return false;
   }

   if(a_length < b_length)
     return true;

   return false;
}
Sign up to request clarification or add additional context in comments.

4 Comments

So, how and where do I integrate this onto my code?
x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase() before comparing it, do var X = x.innerHTML.split('.') and var Y = y.innerHTML.split('.'); and then comparator(X < Y) in place of x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()
JavaScript uses the UTF-16 encoding of the Unicode character set, not ASCII. (Java, .NET, VB6,…, too).
yeah you are correct, but Unicode is a superset of ASCII, and the numbers 0–128 have the same meaning in ASCII as they have in Unicode
1

in short create padding with 100000, for example

8.00.6001.18372 => 100008.100000.106001.118372
11.0.15063.0 => 100011.100000.115063.100000

with regex

x = x.innerHTML.replace(/\d+/g, n => +n + 100000);

function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("myTable");
  switching = true;
  //Set the sorting direction to ascending:
  dir = "asc";
  /*Make a loop that will continue until
  no switching has been done:*/
  // get longest version characters for padding
  var padding = '000000000000'; // 12 chars
  while (switching) {
    //start by saying: no switching is done:
    switching = false;
    rows = table.getElementsByTagName("TR");
    /*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;
      /*Get the two elements you want to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      /*check if the two rows should switch place,
      based on the direction, asc or desc:*/
      // the hack, remove dot      
      x = x.innerHTML.replace(/\d+/g, n => +n + 100000);
      y = y.innerHTML.replace(/\d+/g, n => +n + 100000);
     //console.log(x)
      if (dir == "asc") {
        if (x > y) {
          //if so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      } else if (dir == "desc") {
        if (x < y) {
          //if so, mark as a switch and break the loop:
          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;
      //Each time a switch is done, increase this count by 1:
      switchcount++;
    } else {
      /*If no switching has been done AND the direction is "asc",
      set the direction to "desc" and run the while loop again.*/
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}
document.querySelector('#thead').addEventListener('click', function() {
  sortTable(0);
})
table {
  border: 1px solid #dddddd;
  width: 60%;
  border-collapse: collapse;
}

th {
  background-color: #209d9d;
  cursor: pointer;
}

th:hover {
  background-color: #1c8d8d;
}

tr {
  height: 30px;
}

th,
td {
  text-align: center;
  border-collapse: collapse;
  width: 60%;
  border: 1px solid #ddd;
  align: center
}
<table id="myTable">
  <tr><th id="thead">IE Versions</th></tr>
  <tr><td>10.0.8250.00000</td></tr>
  <tr><td>10.0.8400.00000</td></tr>
  <tr><td>10.0.9200.16384</td></tr>
  <tr><td>8.00.6001.18372</td></tr>
  <tr><td>8.00.6001.18702</td></tr>
  <tr><td>8.00.7000.00000</td></tr>
  <tr><td>8.00.7600.16385</td></tr>
  <tr><td>9.0.8080.16413</td></tr>
  <tr><td>9.0.8112.16421</td></tr>
  <tr><td>10.0.9200.17609</td></tr>
  <tr><td>11.0.15063.0</td></tr>
  <tr><td>11.0.9600.18697</td></tr>
  <tr><td>8.00.6001.18241</td></tr>
</table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.