Assuming your input array is sorted (and if not, it's easy to make it so), you can do something like the following:
const DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// find the first date that is later than `now` (assumes sorted array of dates)
function getClosestDate(now, dates) {
for (let date of dates) {
if (date > now) return date;
}
}
function formatDate(date) {
let ordinalSuffix;
const d = date.getDate();
switch (d) { // figure out what suffix we need
case 1: case 21: case 31:
ordinalSuffix = "st"; break;
case 2: case 22:
ordinalSuffix = "nd"; break;
case 3: case 23:
ordinalSuffix = "rd"; break;
default: ordinalSuffix = "th";
}
return `${DAY_NAMES[date.getDay()]} ${d}${ordinalSuffix} ${MONTH_NAMES[date.getMonth()]} ${date.getFullYear()}`;
}
const dates = [new Date("2019-12-02"), new Date("2019-12-16"), new Date("2020-01-02"), new Date("2020-01-15")];
const closestDate = getClosestDate(new Date("2019-12-25"), dates);
console.log(closestDate); // 2020-01-02T00:00:00.000Z
console.log(formatDate(closestDate)); // Thu 2nd Jan 2020
If your array of dates is coming from somewhere as strings, it may be useful to parse them into Date objects before processing them further.