Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!