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

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

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 Denunciar

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 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