You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在DataTable.js中实现自然排序?

Implementing Natural Sorting in DataTables.js

Natural sorting fixes the frustrating issue where default string sorting orders numbers like 1, 101, 88 instead of the intuitive 1, 88, 99, 101, 103. It also handles date sorting correctly out of the box. Here's how to set it up:

First, add the core naturalSort function, which handles comparisons for strings, numbers, and dates in a human-friendly way:

function naturalSort(a, b) { 
    // Setup temp variables for comparison evaluation
    var x = a.toString().toLowerCase() || '', 
        y = b.toString().toLowerCase() || '', 
        nC = String.fromCharCode(0), 
        xN = x.replace(/([-]{0,1}[0-9.]{1,})/g, nC + '$1' + nC).split(nC), 
        yN = y.replace(/([-]{0,1}[0-9.]{1,})/g, nC + '$1' + nC).split(nC), 
        xD = (new Date(x)).getTime(), 
        yD = (new Date(y)).getTime(); 

    // Natural sorting for dates
    if (xD && yD && xD < yD) return -1; 
    else if (xD && yD && xD > yD) return 1; 

    // Natural sorting for numeric and string segments
    for (var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
        const xVal = parseFloat(xN[cLoc]) || xN[cLoc];
        const yVal = parseFloat(yN[cLoc]) || yN[cLoc];
        if (xVal < yVal) return -1;
        else if (xVal > yVal) return 1;
    }

    return 0; 
}

Next, register this function as a custom sort type with DataTables so it recognizes the "natural" sort option:

jQuery.fn.dataTableExt.oSort['natural-asc'] = function (a, b) { 
    return naturalSort(a, b); 
}; 

jQuery.fn.dataTableExt.oSort['natural-desc'] = function (a, b) { 
    return naturalSort(a, b) * -1; 
};

Finally, apply this sort type to any column in your DataTable configuration by setting sType: "natural" in the aoColumns array:

aoColumns: [ 
    { "sType": "natural" } 
],

Now, whenever users click to sort that column, it will use natural sorting instead of the default lexicographic sort.

内容的提问来源于stack exchange,提问作者Sunil Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:20:29