これを行う別の方法は次のとおりです。
var compare = function(a, b) {
return a > b ? 1 : a === b ? 0 : -1;
},
compareAlphanumeric = function (a, b) {
alpha = compare(a.alpha, b.alpha);
numeric = compare(a.numeric, b.numeric);
return (alpha === 1 | (alpha === 0 && numeric === 1)) ? 1 : (alpha === 0 && numeric === 0) ? 0 : -1;
};
jQuery.fn.dataTableExt.oSort['alphaNumeric-asc'] = function(a, b) {
var r = /^([A-Za-z]+)([0-9]+$)/,
a = {
"alpha": a.split(r)[1],
"numeric": parseInt(a.split(r)[2], 10)
},
b = {
"alpha": b.split(r)[1],
"numeric": parseInt(b.split(r)[2], 10)
};
return compareAlphanumeric(a, b);
};
jQuery.fn.dataTableExt.oSort['alphaNumeric-desc'] = function(a, b) {
var r = /^([A-Za-z]+)([0-9]+$)/,
a = {
"alpha": a.split(r)[1],
"numeric": parseInt(a.split(r)[2], 10)
},
b = {
"alpha": b.split(r)[1],
"numeric": parseInt(b.split(r)[2], 10)
};
return compareAlphanumeric(b, a); //reverse a and b for desc
};
ここでフィドルを操作する:http://jsfiddle.net/jEqu2/3/
このcompare
関数は、基本的な比較関数です。compareAlphanumeric
次の真理値表に基づいて、1、0、または-1を返します。
/*
Alpha Numeric Result
-1 -1 -1
-1 0 -1
-1 1 -1
0 -1 -1
0 0 0
0 1 1
1 -1 1
1 0 1
1 1 1
*/
実際の作業の大部分は、次のoSort
機能で実行されます。
//First declare a RegExp to split the location into an array of [letter, number]
var r = /^([A-Za-z]+)([0-9]+$)/,
//convert the passed "a" parameter to an object containing its letter and number,
//and parse the number portion to an actual number instead of its string representation.
a = {
"alpha": a.split(r)[1],
"numeric": parseInt(a.split(r)[2], 10)
},
//do the same for b
b = {
"alpha": b.split(r)[1],
"numeric": parseInt(b.split(r)[2], 10)
};
//return the alphanumeric comparison
return compareAlphanumeric(a, b);
降順oSort
では、に渡されるパラメータの順序を切り替えるだけで済みますcompareAlphanumeric
。