Order Data Table Using Vanilla JavaScript on the Client-Side without Utilizing External Libraries

I have spent a considerable amount of time searching the website for a solution to my problem, but unfortunately, I have not been able to find one. The options available are either too complicated, require the use of JQuery or an external library, or simply do not work for me.

I am in need of a JavaScript code that meets the following criteria:

  1. Can be executed on the client side from a bookmark
  2. Easy to comprehend
  3. No reliance on libraries
  4. Capable of sorting an HTML table and highlighting related titles

This project pertains to a Helpdesk software where multiple tickets can be generated due to replies, forwards, or conversations, resulting in a scenario such as:

  • First ticket title: Cannot login
  • Second ticket title: Re: Cannot login
  • Third ticket title: Fw: R: Cannot login

Sorting through these tickets, especially when there are many, can be error-prone and frustrating, particularly during busy periods. Therefore, I am seeking a method to quickly organize and emphasize them with a single click without altering any existing formatting.

The HTML table does not include a header but features the first two rows for headers and filtering functionality. As a result, any code provided should be able to skip over these initial rows.

If you have a suitable code snippet to address this issue, please share it with me.

Answer №1

As a newcomer to Java-scripting, I managed to piece together this solution step by step.

The method involves iterating through a table row by row and extracting the "textContent" from the specified cell in each row. This information is then organized into an array with the cleaned cell as the first level and the entire row as the second level.

The cleaning process involves identifying similar ticket titles by removing occurrences of "Re:" and "Fw:" from the textContent.

var key = rows[i].cells[col].textContent.replace(/[^a-zA-Z0-9: ]/g, '').trim();
key = key.replace(/Fw:/gi, '').replace(/Re:/gi, '').trim();

An array is created while adjusting for the startRow so that it begins at 0.

arr[i - startRow] = [key, rows[i]];

This results in an array structure like this: arr[index] = [key,row]

arr[0] = ['Cannot login','<td>....</td>']
arr[1] = ['next subject','<td>....</td>']

Subsequently, we utilize a basic array sorting function.

arr.sort();

Following this, we remove all but the first two rows of the current table.

    while (tbody.rows.length > startRow) {
        tbody.deleteRow(startRow);
    };

We then reconstruct the table while checking for duplicates and highlighting duplicate entries in yellow.

The complete code snippet is presented below:

javascript :
sortandclean();
function sortandclean() {
    var col = 6; /* title row */
    var startRow = 2; /* to skip the first two rows */
    var arr = []; /* main array which will contains the rows */
    var tbody = document.getElementById('RequestsView_TABLE').tBodies[0];
    var rows = tbody.rows;
    for (i = startRow; i < rows.length; i++) {
        var key = rows[i].cells[col].textContent.replace(/[^a-zA-Z0-9: ]/g, '').trim();
        key = key .replace(/Fw:/gi, '').replace(/Re:/gi, '').trim();
        arr[i - startRow] = [key, rows[i]];
    };
    console.log('rows: ' + rows.length);
    arr.sort(); /* sorting the easy way. works with both texts and numbers */
    while (tbody.rows.length > startRow) {
        tbody.deleteRow(startRow);
    };
    for (i = 0; i < arr.length; i++) {
        rowToInsert = arr[i][1]; /* arr[i][0] has the key and arr[i][1] has the row */
        if (arr[i][0] == lastrow) {
            rowToInsert.cells[col].style.backgroundColor = "yellow";
            tbody.rows[tbody.rows.length - 1].cells[col].style.backgroundColor = "yellow";
        }; /* if the current row have the same clean title highlight both current and previous rows title cell */
        tbody.appendChild(rowToInsert);
        var lastrow = arr[i][0];
        totalRows = i;
    };
    console.log('rows reinserted: ' + (totalRows + 1));
} void(0);

To ensure the code functions properly as a bookmarklet, use block comments for commenting within the code (e.g., /* some comment */)

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

Tips for Preserving the Index of a Multidimensional Array

Initially, my task involved saving the position of '0' within an integer using a standard array. The code provided below loops through an array (of size 8) until it identifies the index where '0' is located and stores it as the position ...

"Exploring the array functionality of Angular's Reactive Forms

I am encountering an issue when trying to access the products array that is located within opticanOrders inside the orderForm. Despite seeing in the console that I should reference the products array like this: orderForm.controls.opticianOrders.controls.p ...

How can I insert my URL into the webPDFLoader feature of LangChain platform?

I need help figuring out how to load a PDF from a URL using the webPDFLoader. Can someone explain how to implement this? Any assistance would be greatly appreciated. I am working on this task in nextjs. Where should I place the pdfUrl variable within the ...

PHP - removing a specific value from a JSON object

My JSON file contains the following data: { "0": { "name": "Test1", "devices": [ { "name": "Test1", "code": "654345", "state": "on" }, { "name": "Tes ...

Can a single endpoint be used to provide files to web browsers and data to REST requests simultaneously?

I recently completed a tutorial that lasted 7 hours on creating a blog, following it almost completely. The only step I skipped was setting up separate client/server hosting as suggested in the tutorial. Instead, I have a single Heroku server serving the c ...

Display the component post retrieval in React Native

In my app, users are required to input a code that triggers a call to an external service for data retrieval. Currently, the code can be entered, the API is called, and the response is received successfully. I also have functionality to poll the API every ...

Sorting an array of objects in Typescript using a dynamic property name for generics

My goal is to develop a versatile, typed function that can arrange an array of objects by a numerical value housed under a dynamically named property within each object. Here is my current progress: export const sortByNumber = <T, K extends keyof T> ...

How can I display different data values on each individual circle counter, rather than all circles showing the same data?

Hey there! I'm trying to get my circular counters to display the counter value that I specify in their class and data-percent. However, currently all four counters are only showing the data from the first counter, even though I've set different d ...

Tips for displaying a page within a parent div upon clicking a button in a child div

Hey there, I'm new to scripting and I've run into a problem. I'm trying to figure out how to load a page in a parent div when clicking buttons in a child div. Specifically, I want to load a specific page in the parent div. Just to clarify, t ...

Ways to revert all modifications to styles implemented using JavaScript

Hey there, just checking in to see how you're doing. I was wondering if there's a way to reset all the styles that have been changed using JavaScript? I'm referring to the styles shown in this photo: https://i.sstatic.net/Zawjt.png Thanks ...

JQuery Form Wizard - Adding a Finish Button Linked to a Page

Having some difficulty linking the finish button on my Jquery Form Wizard within my Flask App to a link. I attempted to test the functionality by creating a simple alert, but that didn't work either. I'm certain that I missed a step somewhere, b ...

The Ajax validation form mistakenly redirects the echoes to a different page instead of the intended page for displaying the output

I am currently working on creating an ajax-form to validate the client-side server of my sign-up form. My goal is to have error messages displayed on the same page where they are triggered, without loading a separate page. Below is the code from my (sign ...

grunt-webpack claims to have completed without any errors, yet it has failed to bundle any files

Over the past week, I've been attempting to get grunt, babel, and webpack to work together smoothly. Despite trying various solutions that I found during my research, nothing seems to be working as intended. Below is the relevant portion of my gruntfi ...

Can a web application determine if Microsoft Excel has been installed?

Currently, I am developing a web application using ASP.NET that includes certain functionalities which rely on Microsoft Excel being installed on the user's device. In case Excel is not available, I would prefer to deactivate these features. I am foc ...

Trying to establish a connection and smoothly scroll to a specific <div> in a separate component on the same page utilizing React <Nav.Link href>

Check out this code snippet: Navigation.js <Navbar.Collapse id="basic-navbar-nav"> <Nav className="mr-auto"> <Nav.Link href="???"> Pokeman </Nav.Link> </Nav> I&apo ...

Is there a way to dynamically inject a stylesheet in NextJS?

I'm facing a challenge in my nextJS application where I need to dynamically load a stylesheet based on the user preference fetched from the database. To achieve this, I have added the stylesheet link in the Head component (next/head) like so: <Hea ...

Press the button to load the following row

Here's how the button below works: it will display the key from the table posts($p), and when clicked, it will show the key of the current post. <button type="button" onclick="location.href ='{$baseurl}/view/{$p.key}/';">Next Post< ...

What is the best way to supply JSON data to the "The Wall" MooTools plugin while feeding?

I came across this amazing plugin called "The Wall" but unfortunately, neither the documentation nor the examples demonstrate how to utilize JSON objects with it. Imagine we have a JSON array like: [ { href : "/my/photo/image1.jpg", title : "Me an ...

Implementing Desktop Alerts for Your Web Platforms without requiring the user to be actively engaged in the application or even logged out of the site

Looking to integrate browser notifications in a ASP.NET MVC Web Application, even when the user is not within the application. Is it possible to achieve this functionality? I have already explored , but need further assistance. If I utilize SignalR for Cl ...

Error: The 'replace' property of null cannot be read in select2

In my Node Express app, I am incorporating select2, and encountering an error when supplying an array as the data source with data: dataBase. The issue arises as Uncaught TypeError: Cannot read property 'replace' of null. Although using an ajax ...