Finding a date closest to a user's next birthday JS

Viewed 58

If I have an unsorted array of future Date objects, what would be the best way to pick out the Date closest to the user's next birthday? For example,

    const dates = [new Date(2023, 12, 23), 
                   new Date(2023, 12, 2), 
                   new Date(2023, 12, 6), 
                   new Date(2023, 10, 23), 
                   new Date(2023, 9, 10),
                   new Date(2023, 8, 1),
                   new Date(2023, 7, 4),
                   new Date(2023, 7, 7),
                   new Date(2023, 1, 1)]
    findClosestDate(new Date(1995, 10, 3)); // should return dates[3]
2 Answers

function findClosestDate(date) {
  const today = new Date()
  const nextDate = new Date(date)
  nextDate.setFullYear(today.getFullYear())
  if (nextDate < today) {
    nextDate.setFullYear(today.getFullYear() + 1)
  }
  console.log(nextDate)
  const dates = [
    new Date(2023, 12, 23),
    new Date(2023, 12, 2),
    new Date(2023, 12, 6),
    new Date(2023, 10, 23),
    new Date(2023, 9, 10),
    new Date(2023, 8, 1),
    new Date(2023, 7, 4),
    new Date(2023, 7, 7),
    new Date(2023, 1, 1)
  ]
  // calculate distance to each date
  const diffs = dates.map(d => Math.abs(nextDate - d))
  // find the lowest
  const best = Math.min(...diffs)
  // get the index of the lowest
  const bestIndex = diffs.indexOf(best)
  // return the best one
  return dates[bestIndex]
}
const result = findClosestDate(new Date(1995, 10, 3));
console.log(result)

The question seems to have a few uncertainties or mistakes in it, as many of the comments have already pointed out. I am now trying to answer the question in the way that I understood the intention of OP to be: "Which of the proposed dates is the one closest to the given birthday in that same year?" Also I assume that OP was not aware that the months counter in new Date() is zero based in JavaScript. Therefore I manually adjusted all dates accordingly.

 const dates = [
    new Date(2023, 11, 23),
    new Date(2023, 11, 2),
    new Date(2023, 11, 6),
    new Date(2023, 9, 23),
    new Date(2023, 8, 10),
    new Date(2023, 7, 1),
    new Date(2023, 6, 4),
    new Date(2023, 6, 7),
    new Date(2023, 0, 1)
  ], bd=new Date(1995, 9, 3); // 3 October 1995
// future birthday; 
const fbd=new Date(dates[0].getFullYear(),bd.getMonth(),bd.getDate());

const closest=dates.reduce((a,c)=>Math.abs(c-fbd)<Math.abs(a-fbd)?c:a);

console.log(closest.toLocaleString());

Related