Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda