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);
}
}