Jump to content
Sign in to follow this  

Mark Davis

Recommended Posts

How to sort large tables in HTML using the DOM elements and very little overhead.

I created this Javascript routine in order to sort a massive table with many rows of data that is fast as uses as little data as possible.

I just wanted to share it with the world.

I am using JQuery but anyone can figure out what I did.  If's fast and efficient.

Basically I grab the column name from the heading clicked, figure out sort direction, take table DOM elements apart and put them in Javascript Array.  I pad number columns so they sort as numbers.  I sort the Array and rebuild the DOM using the Pointer I stored with the Sort Data.

Yes, that easy.  I also remove and add back in the zebra effect.

    $('#table_heading th').click(function() {
        var Class = this.className.split(' ');
        var tr = $('#stage_chart_info tr');
        var SortClass = $('#stage_chart_info .' + Class);
        var SortData = Array.prototype.slice.call(SortClass);
        var forsort = Array();
        var Pre = '';
        if (Class[2] == 'num') {
            var DataMask = $(this).attr('data-mask');
            var MaskLeft = Math.floor(DataMask);
            var MaskRight = Math.floor((DataMask - MaskLeft) * 10);

        for (i = 0; i < SortData.length; i++) {
            var ItemArray = new Array(2);
            if (Class[2] == 'txt') {
                ItemArray[0] = $(SortData).text().toLowerCase();
            } else {
                var SortNumber = NumLeft = $(SortData).text().toLowerCase();
                var NumberLeft = Math.floor(SortNumber);
                var NumberRight = Math.floor((SortNumber - NumberLeft) * 10);
                ItemArray[0] = NumberLeft.toString().padStart(MaskLeft, '0');
                if (MaskRight > 0) ItemArray[0] += '.' + NumberRight.toString().padEnd(MaskRight, '0');
            ItemArray[1] = i;
        tr = $('#stage_chart_info tr').detach();
        $('#table_heading th').removeClass('asc').removeClass('desc').addClass('both');
        switch(Class[3]) {
            case 'both': case 'desc':
            case 'asc':

        var Zebra = 'dark';
        forsort.forEach(function(item) {
            $('#stage_chart_info table').append(tr[item[1]]);
            if (Zebra == 'dark') {
                Zebra = 'light'
            } else {
                Zebra = 'dark';

Edited by Funce
Removed Advertising

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Create New...