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]
probably a simple mistake above! so thankyou for any help on this. also will a time affect the date when its being checked?
You can try using the find()
method (if ecmascript is supported):
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));
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));
you can use includes function.
ri = ["26/12/2016", "27/12/2016", "28/12/2016", "29/12/2016"];
ri.includes("20/12/2016"); //False
ri.includes("26/12/2016"); //True
Alternative to IE indexOf return the position of value.
var pos = ri.indexOf("26/12/2016"); // 0
var pos = ri.indexOf("20/12/2016"); // -1
var pos = ri.indexOf("27/12/2016"); // 1
if(pos > -1){ //is in array }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With