[英]Nodejs: how to make intersection of two arrays of dates
如何正确地做矩阵的交集。 我在 nodejs 工作,我试图比较两个 arrays 以获得相同的元素,即“数组交集”
实际上,这是一个很常见的问题,即使我已经搜索并应用了您提到的解决方案,我仍然不明白为什么我做不到。 我有两个 arrays 日期,我处理的日期格式相同,所以我排除了它不会因为这个原因工作的可能性。
我使用了最常见的解决方案,即使用 filter() 方法过滤数组,并通过 include() 方法验证数组 B 是否包含数组 A 的任何元素。
然后尝试同样的事情,但使用 some() 方法检查数组,直到它返回一个真值。
在我的例子中,我正在做的是通过一系列日期,我生成一个新数组,其中包含从范围开始到结束的日期。
以下代码返回“someDates”中的一个数组,这是试图用“holidaysDates”数组拦截“currentWeek”数组的结果
但我不明白为什么它不起作用?
function getArrayOfRangeDate(startDate, endDate) {
let dates: any[] = [];
let currentDate = startDate;
while (currentDate <= endDate) {
dates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
}
users.map(user => {
let user_id = user.id;
let username = user.username;
let modality = user.modality.name;
isHoliday.forEach((schedule: AttendanceSchedule) => {
let startDate1 = new Date(datestart);
let endDate1 = new Date(dateend);
let startDate2 = new Date(schedule.date_start);
let endDate2 = new Date(schedule.date_end);
const currentWeek: any[] = getArrayOfRangeDate(startDate1, endDate1);
const holidaysDates: any[] = getArrayOfRangeDate(startDate2, endDate2);
const results = currentWeek.filter(o1 => holidaysDates.some(o2 => o1 === o2));
// console.log('sameDates', results);
newListOfSchedule.push({
user_id: user_id,
username: username,
modality: modality,
currentWeek: currentWeek,
holidaysDates: holidaysDates,
sameDates: results
});
});
DEMO简单
const arrayA = [ "2022-12-19T00:00:00.000Z", "2022-12-20T00:00:00.000Z", "2022-12-21T00:00:00.000Z", "2022-12-22T00:00:00.000Z", "2022-12-23T00:00:00.000Z", "2022-12-24T00:00:00.000Z", "2022-12-25T00:00:00.000Z" ] const arrayB = [ "2022-12-19T00:00:00.000Z", "2022-12-20T00:00:00.000Z" ] const results = arrayA.filter(o1 => arrayB.some(o2 => o1 === o2)); console.log('results', results)
总之,我想要做的是通过数组 A 将 go 与数组 B 进行比较,以返回两个 arrays 中相同的元素。
我给你留下了一些链接,它们解释了我觉得有趣的安排的拦截
您正在比较两个 Date对象。 在您的示例代码段中,您正在比较两个strings 。 使用===
比较对象时,实际上是通过引用进行比较。 换句话说,两个对象是相同的,只有当它们是相同的引用时:
const a = new Date();
const b = new Date();
a === b // false, different object references
a === a // true, exact same reference
因此,在比较日期时,您需要将它们转换为原始类型(如字符串或数字):
const results = currentWeek.filter(o1 => holidaysDates.some(o2 => o1.getTime() === o2.getTime()));
我以getTime
为例,它返回一个表示日期的数字,作为自纪元以来的毫秒数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.