gpt4 book ai didi

javascript - ES6 - 获取同一天的所有事件对象[相差小于或等于1天]

转载 作者:行者123 更新时间:2023-12-03 16:29:51 26 4
gpt4 key购买 nike

我有一组事件对象 [javascript - es6]。一个属性是 ActivityTime,我正在寻找获取事件时间为同一天的所有对象的最佳方法。即事件时间差小于或等于1天的所有对象。如果可能的话,我想使用最新的 Es6 功能来完成它,感谢您的帮助。

 const activities =    [
{
"ActivityID": 25,
"AlertType": 1,
"Area": "North",
"ActivityTime ": "2017-02-01T00:01:01.001Z",
"MeasureValue": -1
},
{
"ActivityID": 26,
"AlertType": 1,
"Area": "West",
"ActivityTime ": "2016-04-12T15:13:11.733Z",
"MeasureValue": -1
},
{
"ActivityID": 27,
"AlertType": 1,
"Area": "North",
"ActivityTime ": "2017-02-01T00:02:01.001Z",
"MeasureValue": 3
}

]

这里我期望 ACtivityID 为 25 和 27 的对象,因为它们属于同一日期 [差异小于或等于 24 小时]

如何使用 Es6 功能以最干净的方式做到这一点?

我在下面试过...但没有成功

const datesAreOnSameDay = (first, second) => {
console.log("First Date: " + new Date(first.ActivityTime ));
console.log("Second Date: " + new Date(second.ActivityTime ));
new Date(first.ActivityTime ).getFullYear() === new Date(second.ActivityTime ).getFullYear() &&
new Date(first.ActivityTime ).getMonth() === new Date(second.ActivityTime ).getMonth() &&
new Date(first.ActivityTime ).getDate() === new Date(second.ActivityTime ).getDate();
}

const filtered = activities .filter(datesAreOnSameDay);

console.log(filtered);

我尝试使用一个过滤函数,假设它会分别接受两个对象并检查它们是否具有相同的日期。但不知何故它将第二个参数打印为无效日期。

最佳答案

            const activities = [
{
"ActivityID": 25,
"AlertType": 1,
"Area": "North",
"ActivityTime": "2017-02-01T00:01:01.001Z",
"MeasureValue": -1
},
{
"ActivityID": 26,
"AlertType": 1,
"Area": "West",
"ActivityTime": "2016-04-12T15:13:11.733Z",
"MeasureValue": -1
},
{
"ActivityID": 27,
"AlertType": 1,
"Area": "North",
"ActivityTime": "2017-02-01T00:02:01.001Z",
"MeasureValue": 3
}
]
function filter(arr, arg, _filter){
let ret_arr = []
arr.forEach(element => {
if(_filter(element, arg))
ret_arr.push(element);
});
return ret_arr
}
let new_arr = filter(activities, new Date("2017-02-01T00:00:00.001Z"), (x, y) => {
const gap = Math.abs(new Date(x.ActivityTime) - y) / 3600000
//getting difference in milliseconds, then converting it to hours
if (gap >= -24 && gap <= 24)
return true;
else return false;
});
console.log(new_arr)

您可以遍历您的数组,将 ActivityTime 传递给此过滤函数,并像这样获取具有相似时间的实例

            activities.forEach(elemnt => {
const same = filter(activities, new Date(elemnt.ActivityTime), (x, y) => {
const gap = Math.abs(new Date(x.ActivityTime) - y) / 3600000
//getting difference in milliseconds, then converting it to hours
if (gap >= -24 && gap <= 24)
return true;
else return false;
});
if(same.length > 1){
//do whatever you want
}
});

关于javascript - ES6 - 获取同一天的所有事件对象[相差小于或等于1天],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com