Home > OS >  How to validate that an array with dates is arranged newer to older and vice versa
How to validate that an array with dates is arranged newer to older and vice versa

Time:03-23

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!

CodePudding user response:

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

CodePudding user response:

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.

  • Related