Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the next closest date in MM/DD/YYYY format JavaScript

I have an array of dates formatted as MM/DD/YYYY. I need to find the next closest date in the future starting from today. Say today was 1/22/2016 then 2/19/2016 would return.

2/3/2015
7/5/2015
1/21/2016
2/19/2016
7/1/2016

I've tried doing substrings to get the month, day, year separate and attempting a sort based off those values but surely there has to be a better way.

like image 714
MahoreLee Avatar asked May 29 '16 00:05

MahoreLee


1 Answers

There is no need for a sorting algorithm. You only need to iterate once and find the closest date that is greater or equals today.

Pseudocode

closest <- infinity
foreach date in dates:
    if (date >= now and date < closest) then
        closest <- d
return closest

JavaScript

const dates = [
  '2/3/2015',
  '7/5/2015',
  '1/21/2016',
  '2/19/2016',
  '7/1/2016',
  '10/22/2019',
  '08/12/2019',
];

const now = new Date();

let closest = Infinity;

dates.forEach(function(d) {
   const date = new Date(d);

   if (date >= now && (date < new Date(closest) || date < closest)) {
      closest = d;
   }
});

console.log(closest);
like image 97
Frederik.L Avatar answered Nov 15 '22 20:11

Frederik.L