Let’s say we have an Array of Dates
var dateArr = [new Date("Thu Apr 01 2021 00:00:00 GMT+0200"), new Date("Sat May 01 2021 00:00:00 GMT+0200")];
and an Date Object, which we need to search in the dateArr, for example:
var findDate = new Date("Mon Apr 05 2021 07:50:06 GMT+0200");
And all together we have this PLUS
- a function to return us the nearestDate in dateArr by findDate which can lie in the past or future
var dateArr = [new Date("Thu Apr 01 2021 00:00:00 GMT+0200"), new Date("Sat May 01 2021 00:00:00 GMT+0200")]; var findDate = new Date("Mon Apr 05 2021 07:50:06 GMT+0200"); var result = getNearestDateInDateArrByFindDate(dateArr, findDate); console.log(result); //should print to console: Thu Apr 01 2021 00:00:00 GMT+0200 function getNearestDateInDateArrByFindDate(dateArr, findDate) { var nearestDateInPastOrFuture; ... return nearestDateInPastOrFuture; }
What I tried so far without sucess …
var dateArr = [new Date("Thu Apr 01 2021 00:00:00 GMT+0200"), new Date("Sat May 01 2021 00:00:00 GMT+0200")]; var findDate = new Date("Mon Apr 05 2021 07:50:06 GMT+0200"); function getNearestDateInDateArrByFindDate(dateArr, findDate) { console.log(dateArr); console.log(findDate); var nearestFutureDates = dateArr.filter(dt => dt.getTime() >= findDate.getTime()); var nearestFutureDates = nearestFutureDates.sort((a, b) => a.getTime() - b.getTime()); var nearestPastOrFutureDate = dateArr.filter(dt => dt.getTime() >= findDate.getTime()); var nearestPastOrFutureDate = nearestPastOrFutureDate.sort((a, b) => (findDate.getTime() - a.getTime()) - (findDate.getTime() - b.getTime())); console.log(nearestFutureDates); console.log(nearestPastOrFutureDate); //returns always sat May 01 2021 00:00:00 GMT+0200 } getNearestDateInDateArrByFindDate(dateArr, findDate)
And somehow the snippet doesn’t return Apr 01 but rather April 31?
Advertisement
Answer
We can use Array.sort() to sort by the difference in ms from each date to findDate.
NB: We can get the absolute difference in milliseconds between two dates using
Math.abs(date1 - date2);
So we’ll use this to sort like so:
var dateArr = [new Date("Thu Apr 01 2021 00:00:00 GMT+0200"), new Date("Sat May 01 2021 00:00:00 GMT+0200")]; var findDate = new Date("Mon Apr 05 2021 07:50:06 GMT+0200"); var result = getNearestDateInDateArrByFindDate(dateArr, findDate); console.log(result); //should print to console: Thu Apr 01 2021 00:00:00 GMT+0200 function getNearestDateInDateArrByFindDate(dateArr, findDate) { const sortedByDiff = [...dateArr].sort((a,b) => { // Sort by the absolute difference in ms between dates. return Math.abs(a - findDate) - Math.abs(b - findDate); }) // Return the first date (the one with the smallest difference) return sortedByDiff[0]; }