I've previously written an efficient algorithm for sorting tables (answer). I've adjusted the function for this case:
function sortTable(){
var tbl = document.getElementById("myTable").tBodies[0];
var store = [];
for(var i=0, len=tbl.rows.length; i<len; i++){
var row = tbl.rows[i];
var sortnr = parseFloat(row.cells[2].textContent || row.cells[2].innerText);
if(!isNaN(sortnr)) store.push([sortnr, row]);
}
store.sort(function(x,y){
return x[0] - y[0];
});
for(var i=0, len=store.length; i<len; i++){
tbl.appendChild(store[i][1]);
}
store = null;
}
To sort the table, use `sortTable();
Explanation of code:
- Two variables are created: HTMLTableSectionElement
tbl
and Array store
.
- A loop walks through all elements of the tBody (=rows), and pushes a new array in
store
, consisting of two elements: [sortnr, row]
.
sortnr
holds the numeric value of the second cell of the row, which is used for the sort function (look ahead)
row
is a reference to HTMLTableRowElement, used later to move the rows.
store.sort(..)
sorts the array store
according to sortnr
(as defined above, #2 of this explanation).
- A loop walks through the sorted array, and appends the rows at the end of the table (
tbl.appendChild
moves the node from the previous location)
Note that elements which don't have a valid number at the 3rd column (cell index 2) aren't moved at all. These stay at the top of the table.
If you want to have the invalid rows located at the end, use:
for(var i=store.length-1; i>=0; i--){
tbl.insertBefore(store[i][1], tbl.rows[0]);
}
Question by Royi Namir (at comments)
youre the man. just one more question : you wrote 'tbl.appendChild
moves the node from the previous location' , and i thoguth to my self
that the action is appendChild - but behind the scenes it moves(!) the
element. I read about it and they said that if its the same object
then it moved. but how dows he knows that its the same object? he
doesnt have any ID or something to recognize ...
Answer:
(Real life example:) Say, you see a apple laying on the table. If you want that same apple to be at the floor, what would you do? pick up the apple and put it at the floor.
The same applies to appendChild
: When you request the node to be appended, the script engine wants to place the node to be placed in the tree. Consequently, the previous node will be removed, because » appendChild
does not copy nodes. «
To copy nodes, the function element.cloneNode()
exists.