javascriptarraysdatefindgetdate

How to find weekends inside a date array in javascript


I have a date array, what I want is to do two things with it.

1.- Tell me how many dates within it are weekends 2.- Create a new arrangement with the dates that are weekends

I tried the following code but I don't know how to return when the weekend is true, as you can see the code only evaluates when getDay is 0 (Sunday) and 6 (Saturday), I would have to find a way to put those that are true inside the array

const attendanceDates = [
  "2022-11-21",
  "2022-11-22",
  "2022-11-24",
  "2022-11-26"
]

const whenIsWeekend = [];
attendanceDates.forEach(element => {

  const date = new Date(element)
  var dayOfWeek = date.getUTCDay();
  var isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0); // 6 = Saturday, 0 = Sunday
  console.log('isWeekend', isWeekend);
  if (isWeekend) {
    whenIsWeekend.push(element)
  }
})


console.log('array of Weekend', whenIsWeekend)

console.log('count weekends', whenIsWeekend.length)

What I hope to return

array of Weekend [
   "2022-11-26"
]
count weekends 1

Thank your in advance


Solution

  • Using the native Javascript date object:

    const attendanceDates = [
      "2022-11-21",
      "2022-11-22",
      "2022-11-24",
      "2022-11-26"
    ]
    
    const weekends = attendanceDates.filter(date => {
        const dateObj = new Date(date)
        const dayOfWeek = dateObj.getUTCDay();
    
        if (dayOfWeek == 0 || dayOfWeek == 6) {
            return true;
        }
    })
    
    console.log(weekends) //["2022-11-26"]
    

    Using moment.js library (ideal if you need to do many date manipulations easily)

    const attendanceDates = [
      "2022-11-21",
      "2022-11-22",
      "2022-11-24",
      "2022-11-26"
    ]
    
    const weekends = attendanceDates.filter(date => {
        const dateMoment = moment(date)
        if (dateMoment.day() == 0 || dateMoment.day() == 6) {
            return true;
        }
    })
    
    console.log(weekends) //["2022-11-26"]