Home > Software design >  the index value is shown on terminal but is undefined while trying to utilize in code
the index value is shown on terminal but is undefined while trying to utilize in code

Time:04-19

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

CodePudding user response:

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>

  • Related