Using Javascript to organize data in a table

I have a basic HTML table setup that looks like this:

    <table id="myTable">
<thead>
  <tr>
    <th class="pointer" onClick="sortTable()">Number</th>
    <th>Example3</th>
    <th>Example2</th>
    <th>Example1</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>101</td>
    <td>TOM</td>
    <td>Not Working</td>
    <td>AUTOMAT-01</td>
  </tr>
  <tr>
    <td>102</td>
    <td>TOM</td>
    <td>Not Working</td>
    <td>AUTOMAT-02</td>
  </tr>
</tbody>
  
</table>

The function for sorting the table in javascript is currently not functioning as expected. I am looking to sort the table in descending order based on the "Number" column. Additionally, I would like to include an arrow next to each column name that allows users to call the sorting function by clicking on the arrow.

function sortTable() {
  var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("myTable");
  switching = true;
  /*Create a loop that continues until
  no switching has been done:*/
  while (switching) {
    //start with no switches:
    switching = false;
    rows = table.rows;
    /*Loop through all table rows (excluding the
    header row):*/
    for (i = 1; i < (rows.length - 1); i++) {
      //assume no need to switch initially:
      shouldSwitch = false;
      /*Retrieve the elements to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[0];
      y = rows[i + 3].getElementsByTagName("TD")[0];
      //check if the rows need to be switched:
      if (Number(x.innerHTML) > Number(y.innerHTML)) {
        //mark as needing a switch and break out of loop:
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /*If a switch is needed, then make the switch
      and mark that a switch has occurred:*/
      rows[i].parentNode.insertBefore(rows[i + 3], rows[i]);
      switching = true;
    }
  }
}

Answer №1

Why choose to swap rows[i + 3] instead of rows[i + 1]? And why stop the loop rather than continue until the end?

function sortTable() {
  var table, rows, switching, x, y;
  table = document.getElementById("myTable");
  /*Create a loop that continues until
  there are no more swaps:*/
  do {
    //initialize switch flag as false:
    switching = false;
    rows = table.rows;
    /*Iterate through all table rows (excluding the
    first row which contains table headers):*/
    for (var i = 1; i < (rows.length - 1); i++) {
      //initialize switch flag as false:
      /*Get the two elements to compare,
      one from the current row and one from the next row:*/
      x = rows[i].getElementsByTagName("TD")[0];
      y = rows[i + 1].getElementsByTagName("TD")[0];
      //check if the two rows should be swapped:
      if (Number(x.innerHTML) > Number(y.innerHTML)) {
        //if so, mark as a switch
        switching = true;
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        rows = table.rows;
      }
    }
    // repeat until no more switches
  } while (switching)
}
<table id="myTable">
<thead>
  <tr>
    <th class="pointer" onClick="sortTable()">Number</th>
    <th>Example3</th>
    <th>Example2</th>
    <th>Example1</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>101</td>
    <td>TOM</td>
    <td>Not Working</td>
    <td>AUTOMAT-01</td>
  </tr>
  <tr>
    <td>102</td>
    <td>TOM</td>
    <td>Not Working</td>
    <td>AUTOMAT-02</td>
  </tr>
  <tr>
    <td>100</td>
    <td>TOM</td>
    <td>Not Working</td>
    <td>AUTOMAT-00</td>
  </tr>
</tbody>
  
</table>

Answer №2

If you took a bit more time to explore the page you were browsing (https://www.w3schools.com/howto/howto_js_sort_table.asp), you would have easily found the solution to your question.

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.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;
      /* 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;
      }
    }
  }
}
    <table id="myTable">
<thead>
  <tr>
    <th class="pointer" onClick="sortTable(0)">Number</th>
    <th>Example3</th>
    <th>Example2</th>
    <th>Example1</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>101</td>
    <td>TOM</td>
    <td>Not Working</td>
    <td>AUTOMAT-01</td>
  </tr>
  <tr>
    <td>102</td>
    <td>TOM</td>
    <td>Not Working</td>
    <td>AUTOMAT-02</td>
  </tr>
</tbody>
  
</table>

Here's the corresponding fiddle link : https://jsfiddle.net/Louf0sc7/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the integration of angular-ui-select into an angular seed project

I set up a new project using the starter template from https://github.com/angular/angular-seed and now I'm attempting to integrate angular-ui-select for dropdown menus. I've added select.js and select.css files to my index.html as well as install ...

Tips for expanding the content of a blogger page to fill the entire frame of the page

Check out this page: . Currently, the video on the page does not fill up the entire screen. Any suggestions for a solution? ...

Automatically initiate a click event when the page is loaded

I'm having trouble getting a click event to trigger on my controller when the page loads. I really just want the checkboxes to be clicked automatically. <!DOCTYPE html> <html > <head> <link rel="stylesheet" type="text/css" ...

Animate the CSS when the content is within the viewport using pagepiling.js integration

I'm currently working on animating content as it enters the viewport. However, I've encountered an issue where jQuery (used to check if the content is in the viewport) isn't functioning properly alongside pagepiling.js (). I suspect this mig ...

The Facebook JavaScript API function FB.api() is limited to posting messages and does not support media attachments

I am attempting to share a message with an mp3 attachment on the active user's wall. It works perfectly fine within Facebook's Test Console, but when I try it from my mobile app, only the message gets posted. Can anyone help me figure out what I ...

Step-by-step guide on positioning an image to show at the bottom of a div

I am trying to create a div that covers 100% of the screen height, with a table at the top and white space below it for an image. However, when I add the image, it ends up directly under the table instead of at the bottom of the DIV. I have searched on G ...

Tips for showcasing an image prior to uploading within a personalized design input file

I am facing an issue with displaying multiple images inside custom style input file labels before uploading them to the database. Currently, the script I am using only displays one image at a time and in random positions. My goal is to have each image ap ...

Is my rtk slice's initial state not being saved correctly in the store?

Currently diving into the world of RTK with typescript. I have created 2 slices - one using RTK query to fetch data (called apiSlice.ts) and another utilizing createSlice for handling synchronous state changes in my todo app (named snackbarSlice.ts). The ...

An exploration of effortlessly moving elements using webdriver.io - the power of

I have been attempting to utilize the drag and drop method in WebDriver.io, but I am encountering issues. I followed the example for drag & drop on this website: https://www.w3schools.com/html/html5_draganddrop.asp. This functionality is essential for ...

Convert the 'value' attribute in HTML into a clickable link

Is there a way to make the output value of an HTML input field into a clickable link? Right now, it appears as follows: <input type="email" class="form-control" name="contactEmail" value="<?php echo $row_rsContactD ...

Can arrays be passed as function parameters in CrossRider without the need to convert them into objects first?

Our team is currently utilizing CrossRider to develop an extension specifically for Internet Explorer. We have a crucial object that is downloaded from , but we are facing an issue where arrays within this object are getting converted into objects with int ...

Is it possible to trigger the @click event in Vuejs when utilizing v-html to render HTML content?

Here is an interesting HTML scenario: errorText: '<a class="button" @click.prevent="enableExceedable(issue.mapping)">Enable exceedable limits</a>'; I am trying to insert this string into the following div: <div v-if="hasIssue != ...

Leverage jQuery to automatically submit an ajax form once all ajax requests have been successfully executed

I have integrated a WordPress plugin for store locator on my website. For pages without the interactive map, I have set up a form that serves as a location search tool. To clarify, the form includes a location field where users can input their desired loc ...

Tips for utilizing javascript document.createElement, document.body, and $(document) in an HTML web resource for Microsoft CRM code reviews

Let me start off by saying that I am not a regular blogger and I am feeling quite confused. If my question is unclear, please provide guidance for improvement. I recently submitted a Microsoft CRM PlugIn to the Microsoft Code Review. I am new to Javascrip ...

Using react-router to fetch data from the server side

I have successfully implemented React-router server-side rendering in my express app using the following code snippet: app.use((req, res) => { match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { console.log(renderProps) ...

Use PipeTransform to apply multiple filters simultaneously

Is it possible to apply multiple filters with PipeTransform? I attempted the following: posts; postss; transform(items: any[]): any[] { if (items && items.length) this.posts = items.filter(it => it.library = it.library ...

Switching from React version 15.6.2 to 16 results in disruptions to the functionality of the web

Currently, I am encountering an issue where none of my index.js files are rendering. After using the react-scripts to build my web application in version 16.2.0, I receive an error stating that r.PropTypes is undefined when trying to access the localhost a ...

Retrieve data from multiple JSON tables using a JavaScript loop

Check out this Codepen for a working example. I am relatively new to Javascript, so I may not be approaching this problem the best way. If you have any suggestions on how I could improve my approach, I would greatly appreciate it; always looking to learn ...

Does jqgrid navgrid have an event called "on Refresh"?

Is there a way to trigger an event before the grid automatically refreshes? I am looking for something similar to "onSearch" but for the reset button. Below is the code snippet for the navgrid: $("#jqGrid").jqGrid('navGrid','#jqGridPag ...

AngularJS does not update values properly if there is a style applied to the parent container

I'm struggling to find the best approach to handle this situation. This is how my AngularJS code looks: <span class="something" ng-hide="onsomecondition"> {{value}} </span> .something{ text-align:left; padding:10px;} Issue: The value ...