5

I am using DataTables v1.10. I want to make a column sortable by a numeric value, when the value shown in the column is not numeric.

I understand that I need to use orthogonal data to do this, as described here.

However, my sort function is not working. This is my code:

var myData = [{
    'country': 'France',
        'all_games': 7,
        'won_games': 4
}, {
    'country': 'England',
        'all_games': 13,
        'won_games': 13
}, {
    'country': 'Germany',
        'all_games': 2,
        'won_games': 0
}];
var columns = [{
    "data": "country",
        "title": "Country"
}, {
    "data": "outcomes_str",
        "title": 'Games won',
        "render": {
        "_": "display",
            "sort": "sort"
    }
}];
$.each(myData, function (i, d) {
    d.outcomes_str = {};
    d.outcomes_str.sort = (d.all_games > 0) ? (d.won_games / d.all_games) * 100 : 0;
    d.outcomes_str.display = d.won_games + '/' + d.all_games + ' (' + Math.round(d.outcomes_str.sort * 10) / 10 + '%)';
    console.log(d.outcomes_str);
});
drawTable(myData, 'localTable');

function drawTable(data, tableId) {
    var html = '<table class="table table-bordered table-hover ';
    html += '" cellspacing="0" width="100%" id="myTable"></table>';
    $('#table').append(html);
    $("#myTable").DataTable({
        data: data,
        columns: columns,
        paging: false
    });
}
});

JSFiddle here: http://jsfiddle.net/07nk5wob/33/

What am I doing wrong?

1 Answer 1

10

See my corrected answer.

Basically, you need to explicitly state column data type with type: "num" for numeric data, otherwise it may default to alphabetical sort.

{
    "data": "outcomes_str",
    "title": 'Games won',
    "type": "num",
    "render": {
        "_": "display",
        "sort": "sort"
    }
}

See updated jsFiddle for code and demonstration.

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

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.