简而言之:我正在寻找在某个阈值内firstDateList
具有匹配日期的所有日期secondDateList
(可能从几秒到几分钟不等)(感谢@gloo 的评论)。
我正在努力弄清楚有两个日期列表的一些基本内容(我使用momentjs)。(这是为了在 highcharts 图表上显示特定点)。
我必须遍历每个第一个日期,并找到与第二个日期列表匹配的日期。问题是,我可以得到彼此相似的日期,因此它们可以稍微偏离(以前只需要获得准确的 (isSame) 日期,但现在这行不通,因为有些日期偏离了几秒钟分钟)。
我正在检查每个之间的差异,但我不完全理解只获取我需要的日期。
现在它返回每个点直到“secondDateList”中的第一个日期(命名令人困惑,抱歉)
关于在两个列表中仅获取匹配(最接近每个)日期的任何想法?
我对两个数组都使用 forEach 是否正确?我不完全知道如何只将相似的日期推送到新数组中。
我想我应该在第一个数组中进行过滤,以便返回与我想要的日期匹配的新日期数组?我已经不太确定了。。
const closestDatePoints: GraphPoint[] = [];
let closestPointDifference: number | null = null;
firstDateList?.forEach((firstDate, index) => {
const formattedFirstDate = moment(firstDate[0]); // this just gets the date from this firstDate object
secondDateList?.forEach((secondDate, index) => {
// const isSame = date.isSame(formattedFirstDate);
const differenceInMinutes = Math.abs(
moment(secondDate)?.diff(formattedFirstDate, 'minutes')
);
if (
closestPointDifference === null ||
closestPointDifference > differenceInMinutes
) {
closestPointDifference = differenceInMinutes;
// I realize that this is pushing dates that I also do not
// want - its pushing all dates until the first, firstDate, and
// stopping once it hits that first firstDate. Don't know how
// to make it return ***only*** the dates I need.
closestDatePoints.push(firstDate);
}
});
});
这个问题就像找到两个数组的交集,除了值可以在阈值内而不是严格相等。这是一种非常简短且简单的幼稚方法:
const closestDates = firstDateList.filter((date1) =>
secondDateList.some((date2) => Math.abs(date1.diff(date2)) < threshold)
);
我还不能在实际日期上对此进行测试,这远非最快的方法,所以我不确定它是否适用于您的情况,但对于小型数组,这是非常易读的。
如果您需要更快的性能,您首先需要确保两个数组都已排序,以防止一些冗余比较
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句