假设我有一个包含几个对象的数组:
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。
我会使用排序函数和自定义比较器吗?
当前回答
如果像我一样,你有一个日期格式为YYYY[-MM[-DD]]的数组,你想在不太特定的日期之前排序更具体的日期,我想出了这个方便的函数:
function sortByDateSpecificity(a, b) {
const aLength = a.date.length
const bLength = b.date.length
const aDate = a.date + (aLength < 10 ? '-12-31'.slice(-10 + aLength) : '')
const bDate = b.date + (bLength < 10 ? '-12-31'.slice(-10 + bLength) : '')
return new Date(aDate) - new Date(bDate)
}
其他回答
["12 Jan 2018" , "1 Dec 2018", "04 May 2018"].sort(function(a,b) {
return new Date(a).getTime() - new Date(b).getTime()
})
如果像我一样,你有一个日期格式为YYYY[-MM[-DD]]的数组,你想在不太特定的日期之前排序更具体的日期,我想出了这个方便的函数:
function sortByDateSpecificity(a, b) {
const aLength = a.date.length
const bLength = b.date.length
const aDate = a.date + (aLength < 10 ? '-12-31'.slice(-10 + aLength) : '')
const bDate = b.date + (bLength < 10 ? '-12-31'.slice(-10 + bLength) : '')
return new Date(aDate) - new Date(bDate)
}
你可以在下划线js中使用sortBy。
http://underscorejs.org/#sortBy
示例:
var log = [{date: '2016-01-16T05:23:38+00:00', other: 'sample'},
{date: '2016-01-13T05:23:38+00:00',other: 'sample'},
{date: '2016-01-15T11:23:38+00:00', other: 'sample'}];
console.log(_.sortBy(log, 'date'));
当您的日期是这种格式(dd/mm/yyyy)时,应该这样做。
sortByDate(arr) {
arr.sort(function(a,b){
return Number(new Date(a.readableDate)) - Number(new Date(b.readableDate));
});
return arr;
}
然后调用sortByDate(myArr);
简单的回答
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变换定义一个自定义的不可枚举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 ] };
详情见http://phrogz.net/JS/Array.prototype.sortBy.js。