skip to Main Content

I want to check an array of dates to see if they are increasing. For example, [’12/12/2023′,’13/12/2023′] would return true. However, [’12/12/2023′,’11/12/2023′] would return false.
I have been playing around with a function suggested by users for checking integer values. I thought I could do the same but use dates instead.

Here is the function:

function isIncreasing(dates) {
    for (var i = 1; i < dates.length; i++) {
        let convertedToDate = new Date(dates[i]);
        //console.log(currentDate);
        if (convertedToDate[i] !== convertedToDate[i - 1] && convertedToDate[i] != convertedToDate[i - 1] + 1) {
            return false;
        }
    }
    return true;
}
console.log(isIncreasing(['12/12/2023','11/12/2023','10/12/2023']))

The function does not work as the above returns true. Any help is appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    I managed to resolve it by converting the date to a timestamp before comparing. This works if the date is in the format (Y-m-d). Here is the final:

    function isIncreasing(dates) {
        let prevDate = new Date(dates[0]).getTime();
        for (var i = 1; i < dates.length; i++) {
            let convertedToDate = new Date(dates[i]).getTime();
            if (prevDate > convertedToDate) {
                return false;
            }
            prevDate = convertedToDate
        }
        return true;
    }
    
    console.log(isIncreasing(['2023/12/12','2023/12/13','2023/12/14','2021/12/12']))
    console.log(isIncreasing(['2023/12/12','2023/12/13','2023/12/14']))
    

  2. Just split the dates by / and compare the numbers:

    const isIncreasing = dates => {
      for(let i=1;i<dates.length;i++){
        const prev = dates[i-1].split('/');
        const curr = dates[i].split('/');
        for(let j = prev.length - 1;j >=0;j--){
           if(+curr[j] < +prev[j]) return false;
        }
      }
      return true;
    }
    
    console.log(isIncreasing(['12/12/2023','13/12/2023']))
    console.log(isIncreasing(['12/12/2023','11/12/2023']))
    console.log(isIncreasing(['12/12/2023','13/12/2023', '11/12/2023']))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search