Search code examples
javascriptecmascript-6ecmascript-5

check date against an array of dates


I am trying to write a function that returns a TRUE or FALSE value based on whether the date is present in the array or not. Currently I have this:

function isInArray(value, array) {
    var a = array.indexOf(value) > -1;

    if (a == false) {
        return false; //DATE DOES NOT EXIST
    }
    else {
        return true; //DATE EXISTS IN ARRAY
    }
}

Now normally I would use a for loop, however I am generating a list of dates between a start date and end date with this while loop:

 while (day > 0) {
     var tDate = new Date(sDate.addDays(dayCounter));
     datesArray.push(tDate);
     day = day - 1; //DEDUCT THE DAYS AS ADDED

     var dateExists = isInArray(value, array);
     if (dateExists == false) {

     }
     else { 
         matchedDays++;
     }
     daysCounter++;
}

this however is not working and always returns FALSE, what do I need to do to make this work and return the correct value?

sample data: ARRAY[26/12/2016, 27/12/2016, 28/12/2016, 29/12/2016]

value passed in [27/12/2016]

  • return TRUE if the value exists in the array
  • return FALSE if the value does not exist in the array

probably a simple mistake above! so thankyou for any help on this. also will a time affect the date when its being checked?


Solution

  • You can try using the find() method (if ecmascript is supported):

    Case: array contains strings

    var array = ["26/12/2016", "27/12/2016", "28/12/2016", "29/12/2016"];
    var value1 = "26/12/2016";  //exists
    var value2 = "26/12/2026";  //doesn't exist
    
    function isInArray(array, value) {
      return (array.find(item => {return item == value}) || []).length > 0;
    }
    
    console.log(isInArray(array, value1));
    console.log(isInArray(array, value2));


    Case: array contains Date objects

    var array = [new Date("December 26, 2016 00:00:00"), new Date("December 27, 2016 00:00:00"), new Date("December 28, 2016 00:00:00"), new Date("December 29, 2016 00:00:00")];
    var value1 = new Date("December 26, 2016 00:00:00");  //exists
    var value2 = new Date("December 16, 2026 00:00:00");  //doesn't exist
    
    
    function isInArray(array, value) {
      return !!array.find(item => {return item.getTime() == value.getTime()});
    }
    
    console.log(isInArray(array, value1));
    console.log(isInArray(array, value2));