Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
the index value is shown on terminal but is undefined while trying to utilize in code

I'm trying to work with some data that has close bindings to dates. As shown in the snippet down below I'm trying to find the index of the closest day to today. I'm using date-fns utility library for this job. While I'm trying to log the closestIndex from it works fine and got an output in the terminal but while I'm trying to utilize the value of closestIndex I got an error that says closestIndex is undefined. Any Ideas would be very appreciated.

import * as dateFns from 'date-fns';

const today = new Date().getTime();
const dates = [
  2022-04-10T14:07:12.276Z,
  2022-04-10T14:07:06.967Z,
  2022-04-10T14:07:04.663Z,
  2022-04-10T14:07:03.040Z,
  2022-04-10T14:07:01.420Z,
  2022-04-10T14:06:59.869Z,
  2022-04-10T14:06:53.223Z
]

const closestIndex = dateFns.closestTo(today, dates);

console.log(closestIndex); // => 0

console.log(dates[closestIndex]); // => undefined could not be used as index value
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should use real Date objects inside your array (rather than ISO-8601 values which are not even quoted) and use closestIndexTo instead of closestTo (which will return the Date value itself rather than its index in the array)

const today = new Date().getTime();
const dates = [
  new Date('2022-04-10T14:07:12.276Z'),
  new Date('2022-04-10T14:07:06.967Z'),
  new Date('2022-04-10T14:07:04.663Z'),
  new Date('2022-04-10T14:07:03.040Z'),
  new Date('2022-04-10T14:07:01.420Z'),
  new Date('2022-04-10T14:06:59.869Z'),
  new Date('2022-04-10T14:06:53.223Z')
]

const closestIndex = dateFns.closestIndexTo(today, dates);

console.log(closestIndex); // => 0

console.log(dates[closestIndex]); // => "2022-04-10T14:07:12.276Z"
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!