将数据表处理中的字母数字排序顺序更改为A-Z,1-9顺序

时间:2018-09-12 12:21:26

标签: javascript sorting datatables

更正我,如果我错了,但似乎数据表按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); 

谢谢

1 个答案:

答案 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
  }]
})

示例:https://jsfiddle.net/2cd5fjk0/305/