0

I'm facing a problem checking whether a date is in my array or not.

I refer to this article How to correctly use JavaScript indexOf in a date array

But when I use it in my project, it always results in -1.

Here's my code

for (var current = dateStart; current <= dateEnd; current.setDate(current.getDate() + 1)) {
    console.log(this.leaveState.currentHoliday.map(Number).indexOf(+current));
}

I need to check whether current date is in currentHoliday array or not.

kboul
  • 13,836
  • 5
  • 42
  • 53
hphp
  • 2,142
  • 2
  • 13
  • 26
  • 2
    Please add your input array – BlackBeard Jul 24 '18 at 08:52
  • Sees like an inefficient way to check for a holiday, converts the entire holiday array on each iteration. Why not iterate over the holiday array once and see if there are any values between the start and end Dates? If the holidays are sorted, you can stop looking as soon as the holiday is after the end date. – RobG Jul 24 '18 at 08:53
  • @RobG so i need 2 loop? nested? is that more efficient than my way? – hphp Jul 24 '18 at 08:55
  • there may be issue of format – Deepak Kumar Jul 24 '18 at 08:57
  • Could you make a working snippet with your relevant HTML, JavaScript, datepickers, and whatever? – Takit Isy Jul 24 '18 at 08:58
  • @DeepakKumar I already print current date and each item in array.. it showsthe exact same format – hphp Jul 24 '18 at 09:02
  • @TakitIsy mmm how to make that? actually i'm never use tools like that here .-. – hphp Jul 24 '18 at 09:04
  • No, you just need one loop. You are converting the entire array of dates to number on every iteration, and if you have a range of 30 days you'll do 30 iterations (and convert all the dates to number 30 times). – RobG Jul 24 '18 at 11:07
  • This would be much easier to answer if we could see the array you're asking about matching. What are the contents of `this.leaveState.currentHoliday`? – Daniel Beck Jul 24 '18 at 11:39

1 Answers1

0

I think mapping doesn't require to loop into your array. and -1 is somehow mean that the date does not exist in your array.

Maybe because in every loop you add a day to it before you see the actual day.

I think you could try:

    var alldays = [...];
    //you should eliminate these two codes
//    datestart = something;
//  dateend = something;
    var holiday;
    for(var i in alldays){
           console.log(alldays.map(Number).indexOf(this.leaveState.currentHoliday));
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • since I use datepicker to choose startdate and enddate, i think i requires more work put all the date between start and end date to an array.. – hphp Jul 24 '18 at 08:57
  • Hi. Please also take a look at this post which touches on Javascript loops https://stackoverflow.com/a/3010848/1219213 – TheRealChx101 Jul 24 '18 at 08:59