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