Junaid Farooq Junaid Farooq - 1 month ago 12
CoffeeScript Question

loop within a loop in javascript

I am trying to run a loop inside a loop to get some valid dates but doesnt seem to work fine. my sample data is like

these are valid days

[ 'Monday', 'Thursday', 'Friday', 'Sunday' ]


and these are valid dates

[ Sun Oct 09 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Mon Oct 10 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Tue Oct 11 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Wed Oct 12 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Thu Oct 13 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Fri Oct 14 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Sat Oct 15 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Sun Oct 16 2016 05:00:00 GMT+0500 (Pakistan Standard Time) ]


What I want to do is: find only those dates on which are equal to vaid days

What am doing is:

_valid_dates = (dates, days) ->
validDates = dates
dates.forEach (date) ->
days.forEach (day) ->
if moment_strf(date).strftime("%A") != day
validDates.remove date
else
console.log "Am valid day", moment_strf(date).strftime("%A")

validDates


But the results are not coming as I am expecting. According to data the remaining dates should be

[ Sun Oct 09 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Mon Oct 10 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Thu Oct 13 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Fri Oct 14 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Sun Oct 16 2016 05:00:00 GMT+0500 (Pakistan Standard Time) ]


Any help will be appreciated! Thanks

Answer

You can do it simply using only javascript:

Instead of taking full names in day array you can use 0-6 for days and then

    //sunday=0,monday=1 ....saturday=6
     var days=[1,4,5,0];
     var result_arr=[]; // required array for result
     for(date in dates)
     {
        if(days.indexOf(new Date(date).getDay())!=-1)
         {
             result_arr.push(date);
         }
      }