自定义比较器采用以下形式:
myArray.sort(function(a,b){
var m1=a1.RemindingTimestamp,
m2=a2.RemindingTimestamp,
n1=a1.ModificationTimestamp,
n2=a2.ModificationTimestamp;
return m1<m2 ? -1 : m1>m2 ? 1 :
n1<n2 ? -1 : n1>n2 ? 1 : 0;
});
对于降序排序,交换< 和>(或交换1 和-1)。
虽然您可以在每次需要时创建自己的自定义比较器,但我已经创建了一个明确设计的方法,可以使用 Schwartzian transform 轻松按多个标准进行排序(在某些情况下可能会更快但更需要内存): http://phrogz.net/js/Array.prototype.sortBy.js
简而言之:
myArray.sortBy(function(obj){
return [obj.RemindingTimestamp, obj.ModificationTimestamp];
}).reverse();
reverse 在那里,因为您提到您想要降序排序。如果RemindingTimestamp 和ModificationTimestamp 都是数字,您也可以这样做:
myArray.sortBy(function(obj){
return [-obj.RemindingTimestamp, -obj.ModificationTimestamp];
});
以下是将sortBy 添加到数组的代码:
(function(){
// Extend Arrays in a safe, non-enumerable way
if (typeof Object.defineProperty === 'function'){
// Guard against IE8's broken defineProperty
try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
}
// Fall back to an enumerable implementation
if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;
function sb(f){
for (var i=this.length;i;){
var o = this[--i];
this[i] = [].concat(f.call(o,o,i),o);
}
this.sort(function(a,b){
for (var i=0,len=a.length;i<len;++i){
if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
}
return 0;
});
for (var i=this.length;i;){
this[--i]=this[i][this[i].length-1];
}
return this;
}
})();
以下是文档中的更多示例:
var a=[ {c:"GK",age:37}, {c:"ZK",age:13}, {c:"TK",age:14}, {c:"AK",age:13} ];
a.sortBy( function(){ return this.age } );
--> [ {c:"ZK",age:13}, {c:"AK",age:13}, {c:"TK",age:14}, {c:"GK",age:37} ]
a.sortBy( function(){ return [this.age,this.c] } );
--> [ {c:"AK",age:13}, {c:"ZK",age:13}, {c:"TK",age:14}, {c:"GK",age:37} ]
a.sortBy( function(){ return -this.age } );
--> [ {c:"GK",age:37}, {c:"TK",age:14}, {c:"ZK",age:13}, {c:"AK",age:13} ]
var n=[ 1, 99, 15, "2", "100", 3, 34, "foo", "bar" ];
n.sort();
--> [ 1, "100", 15, "2", 3, 34, 99, "bar", "foo" ]
n.sortBy( function(){ return this*1 } );
--> [ "foo", "bar", 1, "2", 3, 15, 34, 99, "100" ]
n.sortBy( function(o){ return [typeof o,this] } );
--> [1, 3, 15, 34, 99, "100", "2", "bar", "foo"]
n.sortBy(function(o){ return [typeof o, typeof o=="string" ? o.length : o] })
--> [1, 3, 15, 34, 99, "2", "100", "bar", "foo"]
请注意,在最后一个示例中,(typeof this) 恰好与
(typeof o);有关详细信息,请参阅this post。