[英] How to sort an object array by date property?
假设我有几个对象的数组:
var array = [{id: 1, date: Mar 12 2012 10:00:00 AM}, {id: 2, date: Mar 8 2012 08:00:00 AM}];
如何按日期元素对数组进行排序,从最接近当前日期和时间的日期开始排序?请记住,数组可能有许多对象,但为了简单起见,我使用了2.
我会使用排序函数和自定义比较器吗?
假设我有几个对象的数组:
var array = [{id: 1, date: Mar 12 2012 10:00:00 AM}, {id: 2, date: Mar 8 2012 08:00:00 AM}];
如何按日期元素对数组进行排序,从最接近当前日期和时间的日期开始排序?请记住,数组可能有许多对象,但为了简单起见,我使用了2.
我会使用排序函数和自定义比较器吗?
array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
array.sort(function(o1,o2){
if (sort_o1_before_o2) return -1;
else if(sort_o1_after_o2) return 1;
else return 0;
});
或者更简洁地说:
array.sort(function(o1,o2){
return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});
在所有数组上使用Schwartzian transform定义自定义的不可枚举sortBy
函数:
(function(){
if (typeof Object.defineProperty === 'function'){
try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
}
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;
}
})();
这样使用:
array.sortBy(function(o){ return o.date });
如果你的日期不是直接可比的,那就做一个可比的日期.
array.sortBy(function(o){ return new Date( o.date ) });
如果返回一个值数组,还可以使用此选项按多个条件进行排序:
// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };
See 100 for more details.