javascriptmomentjsluxon

how to find the nearest date in an array?


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
      }) 
    } 
    }
  }

Solution

  • 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. Using reduce(), find the index of the date with the smallest difference and return the date at the index with the smallest difference.

    const dateSwitch = (prev: boolean) => {
     let newDate: string = DateTime.fromJSDate(new Date()).startOf("day").toISO();
     if (enabledDates.value.length) {
       let selectedDate = DateTime.fromISO(newDate);
       let dates = enabledDates.value.map(date => DateTime.fromISO(date));
       let differences = dates.map(date => selectedDate.diff(date, 'days').days);
       let minIndex = differences.reduce((minIndex, diff, index) => diff < differences[minIndex] ? index : minIndex, 0);
       return dates[minIndex].toISO();
     }
    }