Generate a new table based on the decreasing total of rows from the initial table

I have initially created a table using the rcm.create() method. Now, I need to create another table where the rows are ordered based on the descending sum of the rows from the first table. To achieve this, I will utilize the rcm.generateTab2() method which follows these steps:

1. Call the rcm.create() method to create the second table.

2. Calculate the sum of each row from the first table and store it in a rank array containing objects.

3. Sort the rank array in descending order based on the sum value.

The rank array now contains objects with three elements:

- The first td value from each row

- The sum of the rows

- The complete row to be inserted in the tbody of the second table

4. Delete the tbody element from the second table.

5. Create a new tbody and attempt to insert the sorted rows from table 1 into table 2.

However, when implementing this, the table 2 appears above table 1 in the browser and no rows are inserted.

If you want to view the full code, click here: jsfiddle

The main issue lies within the rcm.generateTab2 method, so I am addressing it separately below.

rcm.generateTab2 method:


generateTab2:function(){
    var power=0;
    this.create(machine,process); //create the second table

    var tbody=document.getElementsByTagName('tbody')[0];
    var trow=tbody.getElementsByTagName('tr');

    for(i=0;i<trow.length;i++){  
        var td=trow[i].getElementsByTagName('td');
        var sum=0;

        for(j=td.length-1;j>0;j--){
            if(td[j].innerHTML==''){
                sum+=0*Math.pow(2,power);
            }else{
                sum+=parseInt(td[j].innerHTML)*Math.pow(2,power);
            }
            power++;
        }
        var first=parseInt(td[0].innerHTML);
        rank.push({rowNo:first,sum:sum,row:trow[i]});
        power = 0;
    }

    rank.sort(function (a,b){
        if(a.sum>b.sum){
             return -1;
        } else if(a.sum<b.sum){
             return 1;
        } else {
            return 0;
        }
    });

    console.log(rank);

    var parent=document.getElementsByTagName('table')[1];
    parent.removeChild(parent.childNodes[1]);

    var newTbody=document.createElement('tbody'); 
    parent.appendChild(newTbody); 

    for(i=0;i<rank.length;i++){
        newTbody.appendChild(rank[i].row);
    }
}

Answer №1

Having some doubts about my grasp on the ranking math.

Take a look at the demo below and also on jsfiddle.

I decided to rewrite your js for simplicity's sake. (If you prefer not using jQuery, I can review your code and identify any issues.)

The libraries I'm using are:

  • jQuery for DOM manipulation
  • Underscore for array creation with _.range (although a for loop could suffice)
  • Tinysort jQuery plugin for table sorting

To facilitate table sorting, I've included the sum of each row as a data attribute so tinysort can arrange the table accordingly.

The CSS here at SO differs slightly from that at jsFiddle (uneven text alignment in headers). Unsure why this is happening.

The preset values (3 & 2) in the form inputs are just for debugging convenience. Feel free to remove the value attribute later on.


Update 07.04.2015

I've identified the problem in your code. The issue arose due to storing the reference to table1 within your rank object. The tr elements were impacted by that reference, causing conflicts with table1.

You can resolve this by using rank[i].row.cloneNode(true) to duplicate the row contents. This way, you can append it to your new table without any complications.

View the updated fiddle here.

[JavaScript, CSS, and HTML code snippets available]

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

Sending a form from an iPhone device to a PHP backend server

It seems like I'm overlooking a simple aspect... Here is a basic form that I want to submit to a PHP script. It works perfectly on PC and Mac, but it doesn't function properly in Safari on iPad, iPhone, etc. Do you think there's some mobile ...

Reflection effect on the ground in three.js

Is there a way to achieve the same effect without duplicating spheres? I attempted to replicate the functionality, but the reflections appear too large :/ var groundTexture = THREE.ImageUtils.loadTexture( "files/checkerboard.jpg" ); groundTexture.wrapS = ...

Issue: Duplicate modules found in CKEditor 5 causing errors

Looking for assistance with integrating CKEditor 5 into a web application built with Vue.js and Laravel. To install the necessary dependencies, I used the following command: npm install --save @ckeditor/ckeditor5-vue @ckeditor/ckeditor5-build-classic as ...

Tips for integrating Twilio Notify with Firebase Cloud Messaging for successful communication

Currently, I am working my way through the Twilio firebase quickstart tutorial until step 7. This step involves the final push notification test, but I am feeling a little confused about the connection between "identity" and "address". From what I understa ...

Starting objects before utilizing them in the useFrame() function in react-three-fiber

I am currently working on a project using react-three-fiber to create a scene. However, I am facing an issue with placing 3D objects at different random positions. I tried using a for loop inside useFrame to set random positions, but this causes the partic ...

Is the utilization of the React context API in NextJS 13 responsible for triggering a complete app re-render on the client side

When working with NextJS 13, I've learned that providers like those utilized in the React context API can only be displayed in client components. It's also been made clear to me that components within a client component are considered part of the ...

Issue encountered: An error occurred while attempting to define a 2-dimensional array within a switch statement in C due to the expected expression missing before the '{' token

I am currently working on a C project, but my partner and I are facing an error that we can't seem to solve. The error message indicates that there is a problem with an expected expression before '{' in the switch_statement whenever we try t ...

What is the reason for initializing I with the length of the response?

I am attempting to generate a table using an AJAX JSON response, but the for loop sets i to the maximum value right away. $.ajax(settings).done(function (response) { console.log(response); var i = ""; td = document.createElement('td'); t ...

Is it possible for me to retrieve an array as a return value from a function in the C programming

My goal is to retrieve an array from a function, but I am facing an issue where only the first element of the array is being returned. This is the code snippet causing the problem: int* getDate() { time_t t = time(NULL); struct tm tm = *localtime ...

Add JavaScript code to your project without bundling it as a module

Is it possible to incorporate a JavaScript library into webpack that is not structured as a UMD-compatible module (AMD, CommonJS)? I want the library to be included in a <script> tag only when necessary and managed by webpack without passing through ...

"Troubleshooting a 400 Bad Request Error in Node.js and Express for a

It seems like I must be making a silly mistake, because this should be a simple task. All I want to do is send a POST request in an Express route. This is my app.js: var express = require('express'); var path = require('path'); var f ...

Extracting address from a string containing HTML line breaks and apostrophes using JavaScript

I need help with parsing an address that is in a string format like the following: "1234 Something Street<br>Chicago, IL 34571<br>" I am struggling to extract and assign it to separate variables: var street = ...; var city = ...; var state = ...

Looking for a method to substitute "test" with a different value

Showing a section of the menu using <li id="userInfo" role="presentation" data-toggle="tab" class="dropdown"> <a href="#" name="usernameMenu" class="dropdown-toggle" data-toggle="dropdown" role="button"> <span class="glyphicon glyph ...

Transform a flat 2D shape into a dynamic 3D projection using d3.js, then customize the height based on the specific value from ANG

Currently, I am utilizing d3.js version 6 to generate a 3D representation of the 2D chart shown below. Within this circle are numerous squares, each colored based on its assigned value. The intensity of the color increases with higher values. https://i.ss ...

button that takes you back to the top of a mobile website

I want to customize the Scroll To Top button so that it only appears once the user begins scrolling down, rather than always being visible even when at the top of the page. Just a heads up, I don't have much experience with JavaScript, so I might need ...

Error in Rails app when incorporating Stripe API with Javascript involved

Incorporating Stripe into my rails app using the Koudoku gem has been challenging. When attempting to load the page for capturing user credit card information, I encounter an error in my JS console: Uncaught ReferenceError: $ is not defined (anonymous fun ...

Position the text so that it is aligned below and to the right of the text box

I'm currently working on a project in ASP.NET that involves a resizable textbox with a character limit display positioned below and to the right of the box. The challenge I am facing is ensuring this text remains properly aligned as the size of the te ...

How can the label value be updated in a material ui slider component?

code snippet: https://codesandbox.io/s/runtime-worker-kxse3?file=/src/App.js Can anyone help me ensure that the labels in the bubble display the same values as the text (3, 5, 7, 10)? ...

Creating a dynamic table layout with Bootstrap

Can someone help me figure out how to make this table responsive using Twitter Bootstrap 4? Here's the JS Fiddle Link for reference. <div class="some-table-section"> <div class="container"> <table class="table some-table"> ...

Display the menu upon activating the hover event icon using only CSS

Assistance Needed - Unable to activate hover and display the rest of the div I want to activate the hover effect where early levels are visible, and when hovering over the first level, the subsequent levels appear List item body { margin: 3%; } div.ti ...