0

I have some problem to sort a column in jquery data table.

I want to sort the first column ascending/descending.

This is some data from the column (default sorted by desc):

R949
R923
R909
R594
R559
R1017

AS you can see the default Sorting algorithm doesn't work with alphanumeric characters.

This are my settings:

$('#myTable').dataTable({
            "aaSorting": [[0, "desc"]],
            "paging": false,
            "lengthChange": false,
            "searching": true,
            "ordering": true,
            "info": true,
            "autoWidth": false
)}

my wish descending result:

R1017
R949
R923
R909
R594
R559

Anybody have some hint what I do wrong? I also tried to use

"columnDefs": [
{"type": "natural", "targets": 0 }]

But this also doesn't work

1 Answer 1

0

The string your are yousing is calculated:

R0xxxxx < R1xxxxx < R2xxxxxx < R3xxxxx < R4xxxxx < R5xxxxx etc ...

You need to do natural sort:

function naturalSort(a, b) {
        var ax = [], bx = [];

        a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
        b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });
        
        while(ax.length && bx.length) {
            var an = ax.shift();
            var bn = bx.shift();
            var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
            if(nn) return nn;
        }

        return ax.length - bx.length;
    }

    test = [
    "R12",
    "R10",
    "R2",
    "R1",
    "R101",
    "R101",
    "R10"
];

    test.sort(naturalSort);
    document.write("<pre>" + JSON.stringify(test,0,3));

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to tell datatables to ignore the 'R' or to split the String value inside the datatables settings?
It is another question, which you can find answers in the stackoverflow. one of them could be: stackoverflow.com/questions/18554921/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.