Skip to content
Advertisement

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!

Advertisement

Answer

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))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement