patternjavascriptModerate
Sorting an HTML table with JavaScript
Viewed 0 times
sortingwithjavascripthtmltable
Problem
The following code sorts an HTML table with JavaScript (without using any external libraries like jQuery). Are there any shortcomings or possible improvements I could make?
var people, asc1 = 1,
asc2 = 1,
asc3 = 1;
window.onload = function () {
people = document.getElementById("people");
}
function sort_table(tbody, col, asc) {
var rows = tbody.rows,
rlen = rows.length,
arr = new Array(),
i, j, cells, clen;
// fill the array with values from the table
for (i = 0; i b[col]) ? asc : -1 * asc);
});
// replace existing rows with new rows created from the sorted array
for (i = 0; i " + arr[i].join("") + "";
}
}
table {
border-collapse: collapse;
border: none;
}
th,
td {
border: 1px solid black;
padding: 4px 16px;
font-family: Times New Roman;
font-size: 24px;
text-align: left;
}
th {
background-color: #C8C8C8;
cursor: pointer;
}
Name
Surname
Age
Raja
Dey
18
Mamata
Sharma
20
Avijit
Sharma
21
Sharanya
Dutta
26
Nabin
Roy
27
Solution
To speed up the sorting you first have to find what is consuming time. In your case the slower part of your code is:
The reason is that the DOM elaboration is time consuming for the browser.
Here's an updated version that minimizes the access to the DOM:
Proof: http://jsperf.com/table-sorting-stack-overflow
for(i = 0; i "+arr[i].join("")+"";
}The reason is that the DOM elaboration is time consuming for the browser.
Here's an updated version that minimizes the access to the DOM:
function sort_table(tbody, col, asc){
var rows = tbody.rows, rlen = rows.length, arr = new Array(), i, j, cells, clen;
// fill the array with values from the table
for(i = 0; i b[col]) ? asc : -1*asc);
});
for(i = 0; i "+arr[i].join("")+"";
}
tbody.innerHTML = ""+arr.join("")+"";
}Proof: http://jsperf.com/table-sorting-stack-overflow
Code Snippets
for(i = 0; i < rlen; i++){
rows[i].innerHTML = "<td>"+arr[i].join("</td><td>")+"</td>";
}function sort_table(tbody, col, asc){
var rows = tbody.rows, rlen = rows.length, arr = new Array(), i, j, cells, clen;
// fill the array with values from the table
for(i = 0; i < rlen; i++){
cells = rows[i].cells;
clen = cells.length;
arr[i] = new Array();
for(j = 0; j < clen; j++){
arr[i][j] = cells[j].innerHTML;
}
}
// sort the array by the specified column number (col) and order (asc)
arr.sort(function(a, b){
return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1*asc);
});
for(i = 0; i < rlen; i++){
arr[i] = "<td>"+arr[i].join("</td><td>")+"</td>";
}
tbody.innerHTML = "<tr>"+arr.join("</tr><tr>")+"</tr>";
}Context
StackExchange Code Review Q#37632, answer score: 11
Revisions (0)
No revisions yet.