"Utilizing a JavaScript array to track the start of the week and

I am encountering a logic problem with determining the start of the week. Below is a snippet of the code:

WeekStarts(WeekN) {
  let WeekBD = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
  let ArrIndex = WeekBD.findIndex(WeekN);    
    
  for (let u = 0; u < WeekBD.length; u++) {
    if (ArrIndex == 6) {
 
    } else {
    
    }
  }
    
}

When selecting a day from a range of Monday to Sunday, the goal is to then choose that day as the starting point and select the next 5 days of the week.
For example, if Saturday is chosen as the starting day of the week, the total duration would be 5 days, spanning from Saturday to Wednesday, skipping Thursday and Friday.

Answer №1

Give this code snippet a try:

    function GetWeekDays(WeekDay) {
         let DaysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];    
        let Index = DaysOfWeek.indexOf(WeekDay);    
        var i = 1;

        while(i <= 5){
           if(Index > 6){ Index = 0 };
           console.log(DaysOfWeek[Index]);
          i++;
          Index++;
      }
   }

Answer №2

To determine the start and end days, you can utilize the modulo (%) operator, as mentioned in the comments.

const getDaysFrom = (weekday, noOfDays) => {
  const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
  , weekdayIndex = weekdays.indexOf(weekday)

  console.log(
    "Start:", weekday, 
    "Days:", noOfDays, 
    "End:", weekdays[(weekdayIndex + noOfDays - 1) % weekdays.length] 
  )
}

getDaysFrom('Saturday', 5)
getDaysFrom('Thursday', 2)
getDaysFrom('Tuesday', 6)
getDaysFrom('Friday', 4)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for customizing the appearance of date circles and text in Vue V-Calendar.io

On v-calendar.io, there is a demo showcasing the correct display where the date "2018-01-01" has a red background and dark text: However, my display does not match that. I have included Vue.js and v-calendar through CDN, and the page is formatted in HTML ...

JavaScript Array Multiplication Theory

I am working with 2 arrays list1 = ["x","y"] list2 = [ ["5","6","7"],["20","21","22"]] My goal is to create an array of objects like this: [ {list1: x , list2: 5}, {list1: x , list2: 6}, {list1: x , list2: 7}, {list1: y , list2: 20}, {list1: y , l ...

Querying and Retrieving a List of Nested Documents in MongoDB

I have multiple solutions, each of which may contain various projects. To represent this relationship, I opted for embedding the projects within the solution document. For example: [{ _id: "1", solutionTitle: "Some Sample Solution", p ...

The retrieved information remains unchanged even after modifications are made on the subsequent Next.js server-side rendered page

I'm facing an interesting scenario with my application. It consists of two main pages - one displaying user account statistics and the other allowing users to edit these statistics. Both pages are rendered on the server side. When I navigate to the fi ...

What is the best way to retrieve JSON data in a React application?

useEffect(async () => { const fetchPostData = async () => { const response = await axios("") setPosts(response.data) } fetchPostData(); }, []) Rendering : posts.map(post => <li>{post.name} ...

Incorrect color change on button triggered by onMouse actions and state fluctuations

While creating a user profile on my app, I encountered an issue with button coloring. When I try to add color functionality to the button, it turns red instead of green and remains red even when the mouse is not hovering over it. My goal is to have the but ...

Deliver JSX components that match one or more keys in the array of strings

Seeking assistance and guidance here. It seems like I might be overlooking something obvious. I am attempting to create a component that accepts either a string or string Array string[] as a property. const ComponentThatReturnsElement = (someElementName) = ...

Having issues with the background-image style not displaying correctly in the header of an

Trying to update the "background-image:" of a CSS class upon button click. JQuery: $(function() { $('button').on('click', function() { $('.masthead2').css('background-image', 'url("../img/whitehead ...

Is it possible to serialize the entirety of a website's Javascript state, including Closure/Hidden scopes?

My goal is to capture a "snapshot" of a webpage while maintaining its interactive functionality, allowing all Javascript states to be saved and restored. An example scenario where this would be beneficial is when a webpage contains script that utilizes glo ...

Retrieving JSON data using the fetch method in JavaScript

Currently, I am attempting to retrieve a JSON array using AJAX. Upon calling my test.php file, the following content is returned: [{"name":"James","age":24},{"name":"Peter","age":30}] This is the JavaScript code that I am using: var persons = new Array( ...

In need of guidance on displaying real-time console output in a window using Handlebars

Utilizing Handlebars, express, and node.js; I have a shell script set to execute upon completion of an HTML form submission. This script, running on the server, neatly logs its progress using console.log: builder.stdout.on('data', function(data) ...

Encountering an error "[$rootScope:inprog]" while using Angular select with ngModel

I'm still learning my way around Angular, but I have a basic understanding. Right now, I'm working on assigning access points to a building using a <select> element. I've created a simple controller for this task, but it's not fun ...

Creating metadata for a node/npm module build

Looking for a solution to output JSON with build date and updated minor version number using grunt and requirejs for our application. It seems like this would be a common requirement. Any existing tools that can achieve this? ...

Use the on-screen keyboard to move around by using the arrow keys and choose a value from the list to

I am currently working on developing an on-screen keyboard that allows for navigation using arrow keys and selection with the enter key. My goal is to have each selected key append to an input field. Below is the HTML code I have implemented: <div id ...

Preserving Scroll Location Through Back Button Usage and Ajax Manipulation of the Document Object Model

Currently, I am incorporating a feature where results are loaded in using ajax with an infinite scroll. However, there is an issue when a user clicks on an item in the list and navigates away from the page - upon returning by clicking the back button, they ...

Is it possible to merge a variable within single quotes in XPath?

Currently working with nodeJS and experimenting with the following code snippet: for (let i = 1; i <= elSize; i++) { try { let DeviceName = await driver .findElement(By.xpath("//span[@class='a-size-medium a-color-base a-text-normal ...

How does Chrome have the capability to access the gist json file? Isn't that typically not allowed?

Fetching a JSON file from Github Gist can sometimes be straightforward, but in certain situations, I have faced difficulties due to CORS restrictions. This has led me to resort to using JSONP instead. Can you shed some light on why this is the case? ...

Capable of generating an ajax URL parameter conditionally for utilization with jQuery Validate

I am having an issue with my jQuery validation script. What I am trying to achieve is this: when a user clicks the send button, the script will determine whether to execute an if or else statement based on the last portion of a string (isAdd). Subsequently ...

Is there a way to adjust the width of the datepicker on my device?

I've been attempting to adjust the width of the date picker, but I'm having trouble achieving it. Below is my code: import React from "react"; import ReactDOM from "react-dom"; import { DatePicker, RangeDatePicker } from &qu ...

Which method of loading website images is quicker: sequential or parallel, utilizing Javascript?

As I work on developing an AJAX image gallery that preloads multiple large images ranging from 120kB to 2MB before the lightbox appears, a question arises: should these images be loaded sequentially (waiting for one to preload at a time) or in parallel? Wh ...