The closestIndexTo
function from the date-fns
library can be used to find the index of the date closest to a given date from an array of dates. Here is an example of how to use the closestIndexTo
function in TypeScript:
Install the date-fns library using npm or yarn:
21 chars2 lines
or
18 chars2 lines
Import the closestIndexTo
function from the date-fns
library:
index.ts43 chars2 lines
Create an array of dates:
index.ts139 chars8 lines
Call the closestIndexTo
function with the target date and the array of dates:
index.ts97 chars3 lines
The closestIndex
variable will contain the index of the date closest to the targetDate
in the dates
array.
Here is the complete example code:
index.ts322 chars15 lines
gistlibby LogSnag