Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda