I am trying to sort a table with JavaScript.
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];
}
//sort the data according to number
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);
});
//assigning the sorted data in the table
for(var i = 0; i < ar.length; i++) {
allRow[i + 1].innerHTML = ar[i].innerHTML;
}
}
But when I am trying to assigning the sorted data in the table somehow it does not. But If I keep the ar data in a new array and then assign that in allRow it does. I am totally newbie in this. So can anyone please tell me why is this happening?
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];
}
When you copy the elements to the
ararray you are not making copies of the elements, you are only copying the references to the elements. Theararray doesn’t contain elements with the same content as theallRowarray, it contains the same elements.When you change the content of an element in the
allRowarray, it will change in theararray also, as it’s the same element.When you have sorted the array, read the
innerHTMLfrom all rows, then you can write them back: