Home > Net >  Match Function to Apps Script for Finding Closest but Less Than Date
Match Function to Apps Script for Finding Closest but Less Than Date

Time:09-22

I have an array of dates. I have a specific date "Search Date". I want to find the date in the array that is closest to but less than the Search Date and return the index of that date in the array.

Example: Suppose the array of dates is [8/1/21, 8/5/22, 8/5/23], indexed 1,2,3 for sake of example. Suppose my Search date is 9/17/22. The function should find the date 8/5/22 and return the index 2.

In Google Sheets, this is simply the match function: enter image description here

How do I do this (and most efficiently) in Apps Script? The IndexOf() function seems to return only an exact match, which does not work in this case.

Thank you!

CodePudding user response:

Explanation:

The idea would be to compare each date in the array with the search date and select the absolute minimum difference which will be the closest date to the search date:

const checkDif = checkDates.map(d=>searchDate - d).filter(v=>v>0);
const minIndex = checkDif.indexOf(Math.min(...checkDif)) 1;
  • enter image description here

  • Related