JohnnyFaldo JohnnyFaldo - 1 year ago 86
Javascript Question

Javascript Table Sort

I'm trying to implement a table sorting function.

It requires keeping the classes and some data attributes on

's and
's so I'm doing it slightly differently than I've seen in other examples.

I'm using
in the sorting function. The problem I'm having is that after sorting the first and seventh item in the list are out of order - the rest seems to be in order. I've tried altering the sort function using
> <
instead and I have the same result.

Could anyone have a glance over my code and see if there's a glaring mistake I'm missing please?

I've tested in on every column it's always the 1st & 7th.

enter image description here

var sort = function() {

var tbody = document.getElementById(tbody_id),
rows_len = tbody.rows.length,
col_len = tbody.rows[0].cells.length;

//console.log(rows_len, col_len);

var order_hash = [];

//loop rows
for(var i = 0; i < rows_len; i++) {

order_hash[i] = {
html: tbody.rows[i].outerHTML



order_hash.sort(function(a, b) {

var result = a.value.localeCompare(b.value);

return (order == 'asc') ? result : (result == 0) ? 0 : (result < 1) ? 1 : -1;



var html = '';

for(var i = 0; i < rows_len; i++) {
html += order_hash[i].html;

tbody.innerHTML = html;

order = undefined;



Answer Source

You are calling sort method twice (one custom and one standard), so the second sort will sort the order_hash in inconsistent way because:

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Cherry" comes before "banana". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.


Remove the second sort and will work fine.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download