按最近日期排序,发生日期

时间:2017-11-02 09:22:15

标签: javascript arrays algorithm sorting momentjs

我有一个对象数组,每个对象都包含一个日期字段。 我希望按照最近日期的顺序按日期对此数组进行排序。

这必须适用于已经发生并将要发生的日期。

res.sort(function (a, b) {
        return new Date(a.toDate) > new Date(b.toDate) ? -1 : new Date(a.toDate) < new Date(b.toDate) ? 1 : 0;
    });

我目前正在使用此排序功能,但它只按日期排序。 我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用日期的绝对增量和今天的排序。

&#13;
&#13;
var array = [{ toDate: '2017-11-01' }, { toDate: '2017-11-02' }, { toDate: '2017-11-03' }, { toDate: '2017-11-04' }, { toDate: '2017-10-01' }, { toDate: '2017-10-11' }, { toDate: '2017-10-31' }, { toDate: '2017-09-01' }, { toDate: '2017-09-20' }];

array.sort(function (a, b) {
    return Math.abs(Date.now() - new Date(a.toDate)) - Math.abs(Date.now() - new Date(b.toDate));
});

console.log(array);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您必须计算日期和今天的日期之间的差异(以毫秒为单位),包括a和b,并比较差异:

var now = new Date();
now = now.getTime();        // now in ms
res.sort(function (a, b) {
    var aToDate = (new Date(a.toDate)).getTime();
    var bToDate = (new Date(b.toDate)).getTime();
    return Math.abs(aToDate - now) - Math.abs(bToDate - now);
});
相关问题