I have an array of dates.
['2023-06-02T00:00:00.000+03:00','2023-06-02T00:00:00.000+03:00','2023-12-04T00:00:00.000+03:00']
I need that when switching in the date component, I compare the selected date with the given array and give the nearest date if I switched to the right or left
I started making a method. But I don’t understand how to compare this in a cycle
to the left – the date is less, to the right – the date is more
const dateSwitch = (prev: boolean) => {
let newDate: string = DateTime.fromJSDate(new Date()).startOf("day")
if (enabledDates.value.length) {
if (prev) enabledDates.value.forEach((enableDateFromArr,idx) => {
const enableDate = DateTime.fromISO(enableDateFromArr).startOf("day").toISO()
const compare = enableDate >= date.value
})
}
}
}
3
Answers
Convert the selected date and the dates in the array using the
DateTime.fromISO()
. Then, iterate over the array of dates and calculate the difference between each date and the selected date. Usingreduce()
, find the index of the date with the smallest difference and return the date at the index with the smallest difference.Here’s a function in JavaScript that takes an array of ISO date strings and a selected date, and returns the nearest date to the selected date :