chapter

Sort book chapters numerically

  • Author: Colin Marks

Sorts a column containing chapter numbers. This can be most useful when using DataTables for a book or book reference style application. By default, five sections are supported (a.b.c.d.e) with each being upto four-digits long. Those defaults are controlled by constMaxSections and constMaxSectionDigits respectively, and can be easily changed

Plug-in code

jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    'chapter-pre': function(a) {
        function makeFiller(count) {
            return count === 0 ? '' : Array(count + 1).join('0');
        }

        var constMaxSections = 5;
        var constMaxSectionDigits = 4;

        var filler;
        var result = '';
        var sections = a.split('.');

        for (var i = 0; i < constMaxSections; i++) {
            filler = i < sections.length ? constMaxSectionDigits - sections[i].length : constMaxSectionDigits;

            result += filler === 0 ? '' : Array(filler + 1).join('0');
            result += i < sections.length ? sections[i] : '';
        }

        return result;
    },

    'chapter-asc': function(a, b) {
        return a < b ? -1 : a > b ? 1 : 0;
    },

    'chapter-desc': function(a, b) {
        return a < b ? 1 : a > b ? -1 : 0;
    }
});

CDN

This plug-in is available on the DataTables CDN:

JS

Note that if you are using multiple plug-ins, it is beneficial in terms of performance to combine the plug-ins into a single file and host it on your own server, rather than making multiple requests to the DataTables CDN.

Version control

If you have any ideas for how this plug-in can be improved, or spot anything that is in error, it is available on GitHub and pull requests are very welcome!

Example

$('#example').dataTable( {
     columnDefs: [
       { type: 'chapter', targets: 0 }
     ]
  } );