3

Numeric sorting is not working on my dataset. So I made a custom sorting that converts whole string into number then sorts based on that, but for some reasons its not working. What am i missing here?

$.fn.dataTableExt.oSort["test-desc"] = function (x, y)
{

         x = parseInt(x);
        y = parseInt(y);

        if ( x < y)
        {
            return 1;
        }

        return 0;


};

$.fn.dataTableExt.oSort["test-asc"] = function (x, y)
{

    x = parseInt(x);
    y = parseInt(y);

    if ( x > y)
    {
        return 1;
    }

    return 0;

}

$('table').DataTable({
    "pageLength": 300,
    "bLengthChange": false,
    "columnDefs": [
    { "type": "test", targets: 3 }
    ]
});

enter image description here

Both ascending and descending are not working properly. I have checked these functions are being called and properly converting strings to numeric instances.

2
  • For what I see on the image you're parsing strings to number (string to int) that includes "A | % : "? Commented Nov 14, 2017 at 20:09
  • Yes, whatever is in the cell is parsed. Which includes div tags as well. Commented Nov 14, 2017 at 20:42

2 Answers 2

5

jQuery DataTable sort function doesn't return 1 and 0. Instead they return 1 and -1. So modifying the sort function made them work perfectly.

    $.fn.dataTableExt.oSort["test-desc"] = function (x, y)
    {

        x = parseInt(x);
        y = parseInt(y);

        if ( x > y)
        {
            return -1;
        }

        return 1;

    };

    $.fn.dataTableExt.oSort["test-asc"] = function (x, y)
    {

        x = parseInt(x);
        y = parseInt(y);

        if ( x > y)
        {
            return 1;
        }

        return -1;
    }
Sign up to request clarification or add additional context in comments.

Comments

0

The jQuery DataTable sort function does not look 0 or 1, or for 1 or -1 specifically. It looks for either positive or negative values. So you could just do:

$.fn.dataTableExt.oSort["test-desc"] = function (x, y) {
    x = parseInt(x);
    y = parseInt(y);
    return y - x;
};

$.fn.dataTableExt.oSort["test-asc"] = function (x, y) {
    x = parseInt(x);
    y = parseInt(y);
    return x - y;
};

Comments

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.