警告:我不具体了解 jqgrid 库。
不过,一般来说,排序函数应该根据两个传入参数的比较返回 1、0 或 -1。假设升序排序:
- 如果 a
- 如果 a == b,则返回 0
- 如果 a > b,则返回 1
其中<、== 和> 运算符指的是您希望的对象整理顺序,这可能不一定与严格的数学或字符串比较相同。例如,您可能有一个对象要按名称排序,然后是 ID,这将涉及比较具有不同类型的两个不同属性。
在您的情况下,您有两个要排序的轴,“活跃度”和“时间戳”。所以你的第一个问题是:一个活跃的和不活跃的相比应该如何?一次比较一项是没有意义的,除非是为了禁止对不同类型的对象进行排序并抛出错误。
处理完“活跃度”排序后,您可以继续比较非活跃项目的时间戳。
再次,我不知道 jqgrid 具体,但我假设 direction 指的是“升序”或“降序”顺序。这将决定您是返回 1(升序)还是 -1(降序)来处理 a > b 案例。
Demo here.
var i, sortedArray;
var testArray = [
'active',
'2014-06-25 01:23:45',
'active',
'active',
'2013-01-31 12:34:56',
'2014-06-25 02:34:45'];
var comparitor = function(a, b, direction) {
console.log('comparitor(a, b, direction)::', a, b, direction);
// Replace this with whatever test allows you to determine whether you're sorting in ascending or descending order
var after = direction === 'descending' ? -1 : 1;
// If both are active, neither should be reordered with respect to the other
if (a === 'active' && b === 'active') {
console.log('Both a & b are active; returning 0');
return 0;
}
// We know at least one is "inactive". Assume "active" should come before "inactive".
if (a === 'active') {
console.log('a is active; returning -1');
return -1 * after;
} else if (b === 'active') {
console.log('b is active; returning 1');
return after;
}
// We know that neither one is active, and can assume both are date strings. You could convert to dates here, but why, since your dates are already in a format that sorts quite nicely?
if (a === b) {
console.log('a === b; returning 0');
return 0;
}
console.log('a !== b; returning either 1 or -1');
return a > b ? after : -1 * after;
}
sortedArray = testArray.sort(comparitor);
for (i = 0; i < sortedArray.length; i++) {
console.log(i + ' = ' + sortedArray[i]);
}