I'm new to StackOverflow too, and my english maybe be poor, so sorry for the mistakes. I don't know if it is optimized, but you can create a variable called like "closest = null" and another called "difference = 0", then loop over your array subtracting each timestamp from your entered timestamp. For each iteration check if the value of substraction is bigger or lesser then the actual value in variable "distance", if it is, change the variable to that value and the variable "closest" to the timestamp that you subtract, else continue the loop. Something like:
//initializing example array
const list = [];
data1 = new Date();
data1.setFullYear(2024);
data1.setMonth(7);
data2 = new Date();
data2.setFullYear(2024);
data2.setMonth(8);
data3 = new Date();
data3.setFullYear(2024);
data3.setMonth(9);
list.push(data1, data2, data3);
//initialize variables to store the closest date and the difference between the entered date and the closest date
closest = null;
diff = 0;
//iterate over the array of dates
list.forEach((stamp) => {
//that will be the entered date you want, im using the current date
const data_hoje = new Date();
//if the closest date is null, set the current date as the closest date and calculate the difference between the current date and the closest date
if(closest == null) {
closest = stamp
diff = data_hoje - stamp
} else {
//if the difference between the current date and the closest date is less than the current difference, update the closest date and the difference
if(data_hoje - stamp < diff) {
closest = stamp
diff = data_hoje - stamp
}
}
})
//print the closest date - response is the timestamp of date3
console.log(closest);