Created
March 16, 2022 03:37
-
-
Save miguelmota/28cd8999e8260900140273b0aaa57513 to your computer and use it in GitHub Desktop.
JavaScript get nearest date timestamp from list of date timestamps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function nearestDate (dates, target) { | |
| if (!target) { | |
| target = Date.now() | |
| } else if (target instanceof Date) { | |
| target = target.getTime() | |
| } | |
| let nearest = Infinity | |
| let winner = -1 | |
| dates.forEach(function (date, index) { | |
| if (date instanceof Date) { | |
| date = date.getTime() | |
| } | |
| let distance = Math.abs(date - target) | |
| if (distance < nearest) { | |
| nearest = distance | |
| winner = index | |
| } | |
| }) | |
| return winner | |
| } | |
| // usage: | |
| // const index = nearestDate(dates, timestamp) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
helpful thank you