Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  165] [ 4]  / answers: 1 / hits: 20652  / 8 Years ago, sun, may 29, 2016, 12:00:00

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.


More From » arrays

 Answers
6

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/2035',
'7/5/2035',
'1/21/2036',
'2/19/2036',
'7/1/2036',
'10/22/2039',
'08/12/2039',
];

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);




[#61986] Thursday, May 26, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nicole

Total Points: 648
Total Questions: 95
Total Answers: 103

Location: Turks and Caicos Islands
Member since Sun, Mar 7, 2021
3 Years ago
;