JohnnyFaldo
JohnnyFaldo

Reputation: 4161

Javascript Table Sort

I'm trying to implement a table sorting function.

It requires keeping the classes and some data attributes on <td>'s and <tr>'s so I'm doing it slightly differently than I've seen in other examples.

I'm using localeCompare() 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] = {
                value:tbody.rows[i].cells[column].innerHTML,
                html: tbody.rows[i].outerHTML
            };

        }

        console.log(order_hash);

        order_hash.sort(function(a, b) {

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

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

        });

        order_hash.sort();

        var html = '';

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

        tbody.innerHTML = html;

        order = undefined;
        delete(order_hash);

    };



}();

Upvotes: 0

Views: 1209

Answers (1)

Irvin Dominin
Irvin Dominin

Reputation: 30993

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.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Remove the second sort and will work fine.

Demo: http://jsfiddle.net/wf9o2tg8/

Upvotes: 1

Related Questions