首页 > 解决方案 > 仅从数组中获取最后一个日期

问题描述

我有一个具有 DateTime 的对象数组,如下所示:

[{Date1, Count1}, {Date2, Count2}, ...]

数组中的日期由 Hour (Date2 = Date1 + 1H) 给出,所以我只对 Date 的最后一小时计数感兴趣。

{Date: 2020-03-21T20:00:00Z, Count: 3}
{Date: 2020-03-21T22:00:00Z, Count: 4}
{Date: 2020-03-21T23:00:00Z, Count: 15}
{Date: 2020-03-22T00:00:00Z, Count: 66}
{Date: 2020-03-22T01:00:00Z, Count: 70}

如何减少此数组以仅考虑每天的最后一项?

{Date: 2020-03-21T23:00:00Z, Count: 15}
{Date: 2020-03-22T01:00:00Z, Count: 70}

myArray.groupBy(Date).TakeLast()...

标签: javascriptarrays

解决方案


这是一些仅在对日期进行排序时才有效的代码(如果不是,您可以通过以下方式进行排序dates.sort((a, b) => a.Date.getTime() - b.Date.getTime())

var dates = [
    { Date: new Date("2020-03-21T20:00:00Z"), Count: 3 },
    { Date: new Date("2020-03-21T22:00:00Z"), Count: 4 },
    { Date: new Date("2020-03-21T23:00:00Z"), Count: 15 },
    { Date: new Date("2020-03-22T00:00:00Z"), Count: 66 },
    { Date: new Date("2020-03-22T01:00:00Z"), Count: 70 }
];
var lastPerDay = [];
// just need to set to a value that's impossible to get normally
var prevDate = null;
// go backwards through the array to find the last instance
for (var i = dates.length - 1; i >= 0; i--) {
    // need some way of combining year, month, and date into a value
    var curDate = [dates[i].Date.getUTCFullYear(), dates[i].Date.getUTCMonth(), dates[i].Date.getUTCDate()].join(",");
    // we haven't seen the date before
    if (curDate !== prevDate) {
        // add the day to the front
        lastPerDay.unshift(dates[i]);
        // update the previous date
        prevDate = curDate;
    }
}
console.log(lastPerDay);

推荐阅读