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

123
Visualizações
How to validate that an array with dates is arranged newer to older and vice versa

I am still very much a newbie to JS and had a question for which I cannot find an answer for.

I have an array such as:

[
                2000-03-22 12:00 AM
                2000-03-21 12:00 AM
                2000-03-17 12:00 AM
                2000-03-17 12:00 AM
                2000-03-15 12:00 AM
                2000-03-15 12:00 AM
                2000-03-15 12:00 AM
                2000-03-11 12:00 AM
]

The actual array is much longer. I need to do a for loop (if best) to check if the dates are arranged in a newer to older or older to newer manner. I don't need to sort them using JS, I already have the list sorted by default.

I have done validations between two dates before, however, I am not sure how to approach an entire array of dates.

Thank you in advance!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could make an array with the differences between the dates:

const differences = Array(dates.length-1).fill().map((_, i) => dates[i+1] - dates[i]);

and then just check if either it's all positive (old to new) or negative (new to old)

const isToNew = differences.every(n => n >= 0);
const isToOld = differences.every(n => n <= 0);

of course, if neither are true, it means your dates are not sorted correctly


If you're confident they're already in order and don't care to verify this, then you can simply just sort the first and last date as shown in the other answer.

about 4 years ago · Juan Pablo Isaza Relatório

0

Seems like all you need to do is compare 2 dates (if they're already sorted). The first and last should do it.

let dates = [
  "2000-03-22 12:00 AM",
  "2000-03-21 12:00 AM",
  "2000-03-17 12:00 AM",
  "2000-03-17 12:00 AM",
  "2000-03-15 12:00 AM",
  "2000-03-15 12:00 AM",
  "2000-03-15 12:00 AM",
  "2000-03-11 12:00 AM"
]

let howSorted = arr => new Date(arr[0]) < new Date(arr[arr.length - 1]) ? 'ascending' : 'descending'

console.log(howSorted(dates))

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