javascript - 仅从数组中获取最后一个日期
问题描述
我有一个具有 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()
...
解决方案
这是一些仅在对日期进行排序时才有效的代码(如果不是,您可以通过以下方式进行排序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);
推荐阅读
- apache-kafka - Kafka 流 - 当事件发生的时间相距很远时加入流
- python - 如何从熊猫数据框中删除不在列表中的某些值?
- node.js - mongoose中查询子文档的子文档
- android - 如何在按下按钮时消除声音android
- java - 空指针异常(循环遍历对象数组)
- firebase - 无法从 Firebase 存储下载调整大小的图像
- html - 用点替换滚动条
- arrays - 从 vue 数据对象中的数组中获取数组长度
- python - 如何使用 Python Paramiko 通过 SSH 连接到 Cisco 交换机
- javascript - 为什么在录制远程流时视频不播放?