lionrocker221
lionrocker221

Reputation: 171

How to create an array of numbers of the days of the week (i.e. 0 for sunday, 1 for monday, etc.) 7 days from current date in javascript?

The title may be confusing so I will further explain here. I'm looking to create an array that contains the day of the week of each day that is, for instance, from 2-7 days from the current date. The starting number given is simply an integer from 0-6 corresponding to the days of the week.

Example 1:

Current day of the week: 0 (Sunday)
Output: [2, 3, 4, 5, 6, 0, 1]

Example 2:

Current day of the week: 3 (Wednesday)
Output: [5, 6, 0, 1, 2, 3, 4]

The use of this is to then translate those numbers into the actual names of the days and use those to display some data.

Upvotes: 0

Views: 1178

Answers (2)

Abito Prakash
Abito Prakash

Reputation: 4770

To get the array of days you can use the below function

function getDays(num) {
    const arr = [];
    for (let i = 2; i <= 8; i++) {
        arr.push((num + i) % 7);
    }
    return arr;
}


And to get the day corresponding to a number, you can use this function

function getDay(num) {
    const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    return days[num];
}

Combining these two to get the desired result

const days = getDays(0); // [2, 3, 4, 5, 6, 0, 1];
const displayNames = days.map(getDay); // ["Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "Monday"]

Upvotes: 1

GalAbra
GalAbra

Reputation: 5148

First of all, you need today's index:

const date = new Date();
const todayIndex = date.getDay();
console.log(todayIndex);

Then you can just add today's index to each number in a 0-7 range - and use the modulo operator to make sure you're staying within this range:

const todayIndex = new Date().getDay();
const ans = [...Array(7).keys()].map(x => (x + todayIndex) % 7);

console.log({ todayIndex, ans });

Upvotes: 0

Related Questions