Herick
Herick

Reputation: 217

Take only the days of the month by removing Saturday and Sunday

How can I add only the days of the month in an array removing Saturday and Sunday?

user goes set the month and year and with this month I get the days.

ex:

March 2018

1 2 5 6 7 8 9 12 13 14 15 16 19 20 21 22 23 26 27 28 29 30

Upvotes: 0

Views: 1033

Answers (3)

MaxG
MaxG

Reputation: 1077

Let's say you have a year, a month and the days (dates) of this month:

const y = 2018
const m = 2 //(0 based)
const days = [1, 2, 3, 4, 5, 6, 7...]

now you can map the array of days into date objects:

const dates = days.map(day => new Date(y, m, day))

now you can filter the dates using getDay() which returns day of the week (0 based)

const filteredDates = dates.filter(date => date.getDay() !== 0 && date.getDay() !== 6)

now you can map the dates back to the day of the month

const filteredDays = filteredDates.map(date => date.getDate())

BTW, you can write all of this in a one liner:

const noSundaySaturday = (year, month, daysArray) =>
                    daysArray
                       .map(day => new Date(year, month, day))
                       .filter(date => date.getDay() !== 0 && date.getDay() !== 6)
                       .map(date => date.getDate())

Upvotes: 2

CRice
CRice

Reputation: 32266

You can do this by using the getDay method of the Date object, with the note that 0 and 6 represent Sunday and Saturday respectively. So with that, just iterate through all the days of the month, and exclude those which are a weekend day:

// March 2018
// March -> 2 (months are zero-indexed)

function getWeekdaysInMonth(year, month) {
    const days = [];

    let date = new Date(year, month, 1);
    while (date.getMonth() === month) {
        if (![0, 6].includes(date.getDay())) days.push(date.getDate());
        date.setDate(date.getDate() + 1);
    }
    
    return days;
}

console.log(getWeekdaysInMonth(2018, 2));

That function should work for any year and month.

Upvotes: 0

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

Filter the array of dates based on the predicate which asks if the day is not Saturday (6) or Sunday (0).

const dates = allDates.filter(date => date.getDay() != 6 && date.getDay() != 0)

Upvotes: 0

Related Questions