I’ve got an array of dates for the month of July like so:
const dates = [
{ date: '2023-07-01', available: true },
{ date: '2023-07-02', available: true },
{ date: '2023-07-03', available: true },
{ date: '2023-07-04', available: true },
{ date: '2023-07-05', available: true },
{ date: '2023-07-06', available: true },
{ date: '2023-07-07', available: true },
{ date: '2023-07-08', available: true },
{ date: '2023-07-09', available: true },
{ date: '2023-07-10', available: true },
{ date: '2023-07-11', available: true },
{ date: '2023-07-12', available: true },
{ date: '2023-07-13', available: true },
{ date: '2023-07-14', available: true },
{ date: '2023-07-15', available: true },
{ date: '2023-07-16', available: true },
{ date: '2023-07-17', available: true },
{ date: '2023-07-18', available: true },
{ date: '2023-07-19', available: true },
{ date: '2023-07-20', available: true },
{ date: '2023-07-21', available: true },
{ date: '2023-07-22', available: true },
{ date: '2023-07-23', available: true },
{ date: '2023-07-24', available: true },
{ date: '2023-07-25', available: true },
{ date: '2023-07-26', available: true },
{ date: '2023-07-27', available: true },
{ date: '2023-07-28', available: true },
{ date: '2023-07-29', available: true },
{ date: '2023-07-30', available: true },
{ date: '2023-07-31', available: true }
];
There is an end
date of 2023-07-05
in the first element of the array and a start
date in the second element of the array with the same 2023-07-05
date.
This means there is a checkout on the 5th and a checkin on the 5th so I would like to update the dates array above and set available: false
.
I would like to do this anytime I see this pattern of 2 match dates such as the 2023-07-08
.
const reserved = [
{ start: "2023-07-03", end: "2023-07-05" }, // check out 5th
{ start: "2023-07-05", end: "2023-07-08" }, // check in 5th, checkout 8th
{ start: "2023-07-08", end: "2023-07-10" }, // checkin 8th
{ start: "2023-07-18", end: "2023-07-20" }, // checkin 18th, check out 20th - ignore this completely, no overlap
{ start: "2023-07-22", end: "2023-07-24" }, // checkin out 24
{ start: "2023-07-24", end: "2023-07-26" }, // checkin 24
];
Any idea how I can accomplish this? I have tried a numerous amounts of filtering but I can never figure out the right pattern to update where there are
2 on the same day.
2
Answers
You can run a loop starting from second element of array and keep checking the current element’s start date with previous element’s end date. If they match, update the date array.
Since the dates array is having sequential data, you can easily know at which index an update is required.
You can simply achieve this by using
Array.indexOf()
andArray.lastIndexOf()
methods.Live Demo :