The phenomenon of value loss during the JavaScript table sorting process

I've been attempting to utilize JavaScript to sort a table, and I'm encountering an issue.

function test() {
    var table = document.getElementById("myTable");

    var allRow = table.getElementsByTagName('tr');

    var ar = new Array();
    for(var i = 1; i < allRow.length; i++) {
        ar[i - 1] = allRow[i];
    }

    //sorting the data based on numerical value
    ar.sort(function(l, r) {
        var num1 = parseInt(l.childNodes[1].innerHTML);
        var num2 = parseInt(r.childNodes[1].innerHTML);
        return (num1 > num2) ? 1 : ((num1 < num2) ? -1 : 0);
    });

    //placing the sorted data back into the table
    for(var i = 0; i < ar.length; i++) {
        allRow[i + 1].innerHTML = ar[i].innerHTML;
    }
}

However, when I try to place the sorted data back into the table, it doesn't work. Strangely enough, if I store the ar data in a new array and then assign that to allRow, it works fine. As a beginner, I'm unsure why this is happening. Can someone explain the reason behind this?

var tmp = new Array();
for(var i = 0 ; i<ar.length ; i++){
    tmp[i] = ar[i].innerHTML;
}

for(var i = 0; i < ar.length; i++) {
    allRow[i + 1].innerHTML = tmp[i];
}

Answer №1

Copying elements to the ar array simply copies references, not the actual content of the elements. Each element in the ar array points to the same element in the allRow array.

If you modify an element in the allRow array, this change will also be reflected in the ar array since they share the same reference.

After sorting the array, you can extract the innerHTML from all rows and write them back using the following code snippet:

for(var i = 0; i < ar.length; i++) {
  ar[i] = ar[i].innerHTML;
}
for(var i = 0; i < ar.length; i++) {
  allRow[i + 1].innerHTML = ar[i];
}

Answer №2

Why are you overriding the sort function with your own? The built-in sort function can handle sorting various types of data, such as numeric and alphabetical.

Here's a simplified version:

function test() {

        var table = document.getElementById("myTable");
        var allRow = table.getElementsByTagName('tr');            
        var ar = new Array();

        for(var i = 1; i <= allRow.length; i++) {               
             ar[i-1]=table.rows[i-1].cells[0].innerHTML;                
        }           
        ar.sort();
        //assigning the sorted data in the table
        for(var i = 1; i <= allRow.length; i++) {               
             table.rows[i-1].cells[0].innerHTML=ar[i-1];

        }

   }

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

Json with ExtJs columns data is fully populated

I am having trouble with displaying columns in my jsp which fetches json data. I am retrieving this json data in my javascript and using Ext.data.JsonStore but the columns are not showing up as expected. Here is the code for the store: store = new Ext.da ...

Is it possible to further simplify this piece of JavaScript using jQuery?

In my journey to learn and grow with Javascript, I have come across a snippet of code that simply attaches an onclick event to a button and updates the text of an em tag below it. As I delve deeper into jQuery, I am beginning to appreciate its syntax and u ...

What is the best way to create two MUI accordions stacked on top of each other to each occupy 50% of the parent container, with only their contents scrolling

I am looking to create a layout with two React MUI Accordions stacked vertically in a div. Each accordion should expand independently, taking up the available space while leaving the other's label untouched. When both are expanded, they should collect ...

Sending data to a child component through an onClick event handler

Can someone help me figure out how to make the Overlay inside the InviteButton visible when clicking on it? I want to use the prop show={true}, but I'm struggling with this implementation. Any assistance or guidance would be greatly appreciated. ----f ...

I'm having trouble pinpointing the issue in my JavaScript and HTML code

I'm having trouble in JavaScript trying to get my calculations to show up. The error message in my code says there is a missing variable declaration, but I'm not sure what else to do since I am new to this and have been stuck on it for days. It&a ...

Accessing the Node API with a GET request should be the first step taken before proceeding with

In my front-end setup, I have implemented an interceptor that automatically adds an Authorization header if a JWT token exists. There are 2 APIs in play: one for authorization checks and the other for handling data requests (the focus of my work). My goa ...

"Upon clicking the Bootstrap dropdown button, it mysteriously vanishes from

I am experiencing an issue where the button meant to reveal a dropdown menu is actually hiding the dropdown button itself. Interestingly, another dropdown menu in the same navigation works perfectly fine. <div class="side-nav pull-right"> <di ...

Turn off integrity verification for local dependencies in package-lock.json

Is there a way to bypass the integrity check for a local dependency in package-lock.json? Within my project repository, I have a core library along with two Angular applications that both rely on this core library as a dependency. The problem arises beca ...

Show the list in a circular buffer fashion

I am working on a project that involves creating a unique UI element. In Frame #2 of my professionally designed diagram, I envision a list that functions as a ring buffer/rolodex when it exceeds four items. The list would scroll in a loop with the top and ...

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...

Is it possible to automatically access the most recent Beta build through package.json and npm?

We are currently working on a project that has a specific dependency requirement for the latest beta build from an npm library. However, there are also -dev builds within the library. For instance, in the "x-library" there might be versions like: "1.2.3- ...

JavaScript/Typescript is throwing an error because it is unable to access the property 'username' of an undefined object

In my project, I am attempting to compile a list of Profile objects and then extract specific elements from each object in the list. To accomplish this, I have defined a public interface named Profile, imported it into my component, and instantiated a new ...

What could be causing this JSON object to be returning as undefined?

Is it possible for the value in this JSON to be undefined when I use json.bridge_time? {"tunnel_time": 0,"bridge_time": 0} In case it matters, here is the segment of code where I am making the call: $.get( "http://localhost:8000/us", function(json){ con ...

The table remains visible during an AJAX call

I need assistance with removing a table after successful deletion triggered by an AJAX to PHP call. Below is the function provided: list.php <script type="text/javascript"> function massDelete() { if (!confirm("Are you sure")) ...

Using the getElementById function in javascript to modify CSS properties

Here is the setup I am working with: <div id="admin"> This element has the following style applied to it: display: none; I am attempting to change the display property when a button is pressed by defining and utilizing the following JavaScript co ...

Updating materials within the Forge

Currently, we have implemented a system where the client retrieves object states when the page loads, changing the colors of 'pending' objects in the model. We continue to poll for changes to update the coloring - initially coloring pending objec ...

Utilizing Jquery for efficient event delegation across various elements and events

I need to ask my question quickly because my English is not very good. Is it possible for me to use delegate in this way or is there a similar alternative? $( 'body ').delegate({ 'input[type=text]': { 'change' ...

JavaScript: When utilizing 'this' along with nextSibling, encountering the issue of undefined not being an object

When I run a function on the click of a button in my HTML, I want to retrieve the innerHTML value of the sibling element that was clicked. However, I keep receiving the error message 'undefined is not an object'. Here's how my HTML structure ...

How can I automatically update the preview image on a website shared on Facebook?

I tried the code below, but it doesn't seem to be working. Is it possible to dynamically achieve this? If yes, how can I do it? I initially used the og:image meta tag, but it didn't work due to browsers not reading JavaScript. Any assistance woul ...

What is the best way to trigger a JavaScript function whenever a field reaches a specific length?

I need to update a function that currently triggers when the user clicks or tabs out of the employee_number field. My goal is for it to run whenever the length of the entered numbers reaches 6, without requiring the user to leave the field. When I attempte ...