更正我,如果我错了,但似乎数据表按1-9的字母数字字段排序,然后按A-Z顺序排序。有没有办法改变升序的处理,以便相反。例如,我想要 A1,A3,AA,AZ 以显示为 AA,AZ,A1,A3 。我在Servlet中有代码,该代码对从表中检索到的数据的第一个字符进行集合排序,并将数字移动到比字母高的位置,但是我不想对字段中的所有字符进行此检查。我想要的似乎不是自然排序。
这是我使用的代码:
Comparator<Object> comparator = new Comparator<Object>()
{
@Override
public int compare(Object o1, Object o2) {
A8SPT138 obj1 = (A8SPT138)o1;
A8SPT138 obj2 = (A8SPT138)o2;
if (Character.isDigit(obj1.getAccountingEvent().charAt(0))) {
if (Character.isDigit(obj2.getAccountingEvent().charAt(0))) {
return obj1.getAccountingEvent().compareTo(obj2.getAccountingEvent());
} else {
return -1;
}
} else if (Character.isDigit(obj2.getAccountingEvent().charAt(0))) {
return 1;
}
return obj1.getAccountingEvent().compareTo(obj2.getAccountingEvent());
}
};
Collections.sort(tableData.getRecords(), comparator);
谢谢
答案 0 :(得分:0)
您需要提供一个自定义排序器功能,用于检查项目的每个字符。在代码注释中对其进行解释。
const data = "A1, A3, AA, AZ, A, 3".split(", ")
function sorter (a, b) {
if (a === b) return 0; // a and b same
for (let i = 0; i < a.length; i++) {
if(b[i] === undefined) return 1; // b is shorter so should be first
if(a[i] === b[i]) continue; // same char proceed to the next char
const isANumber = (/\d/).test(a[i]);
const isBNumber = (/\d/).test(b[i]);
if (!isANumber && isBNumber) return -1; // b is a number so it should go after
if (isANumber && !isBNumber) return 1; // a is a number so it should go after
return a[i].charCodeAt() - b[i].charCodeAt() // a and b are of the same type so sort by char code
}
return -1; // a is shorter than b so should be before b
}
console.log(data.sort(sorter))
要使其与DataTables
一起使用,您需要将其注册为自定义排序:
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"letters-over-numbers-asc": sorter,
"letters-over-numbers-desc": sorterDesc,
} );
然后在您的桌子上使用它:
$('#data_table_test').DataTable({
order: [
[0, 'asc']
],
columnDefs: [{
type: "letters-over-numbers",
targets: 0
}]
})