我有兩個日期數組。第一個具有所有預訂日期,第二個具有用戶將選擇的「開始日期」和「結束日期」之間的日期。如何檢查兩個日期數組是否有匹配的項目?
現在我必須確認從完全預訂的日期數組中找不到開始和停止之間的天數。
我正在使用Vue.js來更新數據。
這裏是我做了什麼讓這些日期:
/**
* Get dates from datepicker and format it to the same format that fully booked array has it's dates.
**/
var day1 = moment(this.startDate, 'DD/MM/Y').format('Y,M,D');
var day2 = moment(this.endDate, 'DD/MM/Y').format('Y,M,D');
var start = new Date(day1);
var end = new Date(day2);
/**
* Get dates between start and stop and return them in the dateArray.
**/
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
function getDates(startDate, stopDate) {
var dateArray = [];
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
}
var dateArray = getDates(start, end);
/**
* Set dateArray in to Vue.js data.
**/
this.$set('daysBetweenStartStop', dateArray);
/**
* Get arrays of dates from the Vue.js data. calendar = Booked dates | matchingDays = Dates between start and stop.
**/
var calendar = this.fullDates;
var matchingDays = this.daysBetweenStartStop;
/**
* @description determine if an array contains one or more items from another array.
* @param {array} haystack the array to search.
* @param {array} arr the array providing items to check for in the haystack.
* @return {boolean} true|false if haystack contains at least one item from arr.
*/
var findIfMatch = function (haystack, arr) {
return arr.some(function (v) {
return haystack.indexOf(v) >= 0;
});
};
var matching = findIfMatch(calendar, matchingDays);
/**
* Check the results. If false we are good to go.
**/
if (matching){
alert('WE FOUND A MATCH');
} else {
alert('GOOD TO GO');
}
數組是按以下格式:
var calendar = [
Sun Oct 02 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 09 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 16 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 23 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
]
var matchingDays = [
Fri Oct 28 2016 00:00:00 GMT+0300 (EEST),
Sat Oct 29 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
]
我的問題是,即使這兩個數組具有完全相同的日期,但它們仍然會以某種方式被視爲不相同。任何想法如何得到這個工作?
是數組總是排序嗎? – Gal
你的意思是你需要看到兩個數組之間的區別還是需要看到數組中的匹配項? –
@Gal是的,完全預訂的數組來自其他函數,它過濾來自另一個數組的特定日子,然後將它們設置爲完全預訂的數組。匹配日期數組來自開始日期和結束日期,這將從開始到結束將項目推送到數組。 – Eljas