如何在DataTable.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

