Home > Software design >  How to validate that array of strings is sorted alphabetically or by date in javascript?
How to validate that array of strings is sorted alphabetically or by date in javascript?

Time:07-09

I have array of strings

const array =  [
       ' | 7/9,  5:00 AM',
       ' | 7/10, 5:00 AM',
       ' | 7/10, 11:00 PM',
       ' | 7/13, 2:30 AM'
    ]

and wrote a function

function validateScheduledGamesOrder(arrayWithAiringTimes) {
  if (arrayWithAiringTimes.length === 1) {
    return true;
  }
  for (let i = 0; i < arrayWithAiringTimes.length - 1; i  ) {
    if (arrayWithAiringTimes[i] > arrayWithAiringTimes[i   1]) {
      return true;
    } else {
      return false;
    }
  }
}

But I'm not sure that is correct solution. How I can check that it is sorted correctly alphabetically or by date ? I dont need to sort it, I just need to validate that order is correct

CodePudding user response:

The tricky part will be to parse the dates. Once you have that in place, your function to check for an ascending order will be fine. Although you should allow two consecutive values to be equal as well (as that is still "sorted").

The date format you have there is quite unusual, and it would be better to use a standard format (ISO). If that is really not possible, then you need to write a little parser. Here is one that just extracts the numbers and the "A" or "P" letter near the end, and builds a date object from that:

function parseDate(s) {
    const [month, day, hour, min, merid] = s.match(/\d |[AP]/g);
    return new Date(2020, month - 1, day, (merid == "P") * 12   (hour % 12), min);
}

This parser will not do any input validation; it assumes the provided string has the expected format. It takes a leap year as year, so it can accept 2/29.

The function to test whether an array is sorted, can be written like this:

const isNonDecreasing = array => array.every((val, i) => !i || val >= array[i-1]);   

Combining this, you can have:

function parseDate(s) {
    const [month, day, hour, min, merid] = s.match(/\d |[AP]/g);
    return new Date(2020, month - 1, day, (merid == "P") * 12   (hour % 12), min);
}

const isNonDecreasing = array => array.every((val, i) => !i || val >= array[i-1]);   

// Example run
const array =  [
   ' | 7/9,  12:00 AM',
   ' | 7/10, 5:00 AM',
   ' | 7/10, 11:00 PM',
   ' | 7/13, 12:00 AM',
   ' | 7/13, 2:30 AM',
   ' | 7/13, 11:00 AM',
   ' | 7/13, 12:00 PM',
   ' | 7/13, 1:00 PM',
];

console.log("Is sorted alphabetically?", isNonDecreasing(array));
console.log("Is sorted by date?", isNonDecreasing(array.map(parseDate)));

  • Related