簡而言之:我正在尋找在某個閾值內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);
}
});
});
uj5u.com熱心網友回復:
這個問題就像找到兩個陣列的交集,除了值可以在閾值內而不是嚴格相等。這是一種非常簡短且簡單的幼稚方法:
const closestDates = firstDateList.filter((date1) =>
secondDateList.some((date2) => Math.abs(date1.diff(date2)) < threshold)
);
我還不能在實際日期上對此進行測驗,這遠非最快的方法,所以我不確定它是否適用于您的情況,但對于小型陣列,這是非常易讀的。
如果您需要更快的性能,您首先需要確保兩個陣列都已排序,以防止一些冗余比較
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/490897.html
上一篇:Reactapollo在查詢graphql時發送POST請求而不是GET
下一篇:在反應傳單中內置標記圖示型別
