What is the best way to cycle through an array and automatically start over from the beginning after reaching the end?

Issue at hand:

In my current script, I've defined an array named "weekdays":

const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

Let's say it's Saturday and I need to determine the number of days until Tuesday (which is 3 days). How can I navigate through the array - starting from "Sat" and looping back to the beginning until we reach "Tue"?

The code snippet I've implemented so far:

const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

const start = weekdays.indexOf("Sat"); 
const end = weekdays.indexOf("Tue"); 
let howManyDays = 0;

for (let i = start; i < end; i = (i + 1) % weekdays.length) {
  howManyDays++;
}

But when testing this code in the browser console, it appears that the variable "howManyDays" remains at 0. Any assistance on why this might be happening would be appreciated.

Answer №1

let daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

const totalDays = daysOfWeek.length;        // 7
const startingDay = daysOfWeek.indexOf("Saturday"); // 5
const endingDay = daysOfWeek.indexOf("Tuesday");   // 1

let numberOfDays = 0;

// If the starting day comes after the ending day, then we calculate the difference by taking into account the length of the week.
if (startingDay > endingDay) {
  numberOfDays = (totalDays - startingDay) + endingDay;
}

// If the starting day is before the ending day, then simply subtract one from the other to get the duration between them.
if (startingDay < endingDay) {
  numberOfDays = endingDay - startingDay;
}

// If the starting and ending days are the same, then the result should be zero.
return numberOfDays;                      // 0

One aspect to consider is whether you want the same day to be considered as 0, as demonstrated here, or as 7, if it's designated for next week.

Answer №2

UPDATE

To ensure proper functionality, it is important to consider array wrapping, which was overlooked in the initial response.

Here is a solution that addresses this issue:

const howManyDaysBetween = (start, end) => {
  const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
  const week = weekdays.length;
  const startDay = weekdays.indexOf(start);
  const endDay = weekdays.indexOf(end);
  const howManyDays = startDay > endDay ? (week - startDay) + endDay : endDay - startDay;
  
  console.log(`How many days between ${start} and ${end}?: ${howManyDays}`);
}

howManyDaysBetween("Sat", "Tue")
howManyDaysBetween("Tue", "Sat")
howManyDaysBetween("Mon", "Sun")
howManyDaysBetween("Fri", "Wed")

Answer №3

This particular loop is well-suited for the question at hand. It may seem a bit redundant to use two indexOf functions to determine the distance, but subtracting and taking the modulus of the array length simplifies the process. This method works effectively within the loop since it allows for easy comparison of values until reaching "Tue".

const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

const start = weekdays.indexOf("Sat");
const end = weekdays.indexOf("Tue");
let howManyDays = 0;

for (let i = start; i != end; i++) {
  i = i % weekdays.length;
  howManyDays = howManyDays + 1;
}

console.log(howManyDays)

Answer №4

If you want to calculate the difference in weekdays without using a loop, here is a simple solution for you.

const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

const weekLength = weekdays.length;
const startDate = weekdays.indexOf("Wed");
const endDate = weekdays.indexOf("Thu"); 

const result = (weekLength - startDate + endDate) % weekLength;

console.log(result); // -> 1

Note: The above example will return 0 if the start and end dates are the same. If you want to get 7 instead of 0, you can make a small adjustment as shown below:

const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

const weekLength = weekdays.length;
const startDate = weekdays.indexOf("Sat");
const endDate = weekdays.indexOf("Sat"); 

const result = (weekLength - startDate + endDate) % weekLength;

console.log(!result ? weekLength : result)

Answer №5

If you find yourself in a situation where you need to count using a base-7 numbering system, the code below will make it easy for you:

const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

const start = weekdays.indexOf('Sat');
const end = weekdays.indexOf('Tue') + weekdays.length;

const totalDays = end - start;

console.log(totalDays);

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

Looking to pass multiple props and run a function for each one? Here's how!

There is a scenario where I have two separate times in minutes format that need to be converted to 24-hour format without separators. I am currently using a function for this conversion and then using momentjs to transform it into the required format. Whil ...

The various sections of my website are neatly tucked away under one tab, only revealing themselves to users as they click on each individual tab

My recently published website is experiencing a strange issue. When the site loads, all contents including paragraphs and videos from other pages are displayed under one tab (the HOME tab). However, once any other tab is clicked, the issue fixes itself. Yo ...

adding a JavaScript module to a handlebars template

I have a few different files that I'm working with: In the server.js file, I have the following code: app.get('/main/:id', function(req, res) { res.render('main', { products: products }); }) Within the main.hbs file, I have ...

Combining several SVG images into a single file disrupts the text

In my web app, I utilize SVG files to visually map different types of data onto our experimental dataset. Each SVG file corresponds to a specific type of data and is displayed individually on most pages of the site. These maps include tooltips on nodes for ...

Ways to extract information using Ajax

I am working with a variable named sid that represents the number of seats. My goal is to pass sid to the test method in the TryJSON.aspx file, manipulate the data within the method, and then return the result to the ajax call. However, I encountered an er ...

What are the steps to make a "calculate" button?

My webpage has some variables that take a few seconds to calculate. I want to display the sum of these two variables in a text field, but it needs to have a slight delay (1-2 seconds). I tried using "document.write(var1 + var2)" inside a specific function, ...

What is the syntax for replacing specific letters within a JavaScript string using JavaScript?

When I print data from an external JSON file, I am seeing strange characters like "Ã Å, Ã ¤, Ã ¶" instead of "Å, Ä, Ö". The file seems to have the wrong encoding, but unfortunately, I cannot change it since it is from an API. Is there a simple s ...

Utilizing Javascript to load and parse data retrieved from an HTTP request

Within my application, a server with a rest interface is utilized to manage all database entries. Upon user login, the objective is to load and map all user data from database models to usable models. A key distinction between the two is that database mode ...

Trouble handling Ajax response

I have two JSP files described below. The parent JSP page contains a Select dropdown box with two options. Another JSP file, dispTable.jsp, displays select boxes inside a table. If the user selects "one" from the dropdown in the parent.jsp page, I want ...

What steps should I take to create an object that can be converted into a JSON schema like the one shown here?

I'm facing a rather simple issue, but I believe there's something crucial that I'm overlooking. My objective is to iterate through and add elements to an object in order to generate a JSON structure similar to the following: { "user1": ...

Upon initial startup, the "Get Authenticated" process gets stuck in an endless loop

Upon initially loading my AngularJS application, I am faced with a blank screen and an endless loop attempting to verify the user's authentication status. For this specific project, I have opted for sails version 0.11.0 as well as the latest version ...

Obtain the incremented input's value

Seeking advice: I have a dilemma with two buttons that increase or decrease an input value. How can I retrieve the value upon submission of the result? Previous attempts have yielded 'undefined' or '0' values. Your insights and guidanc ...

The error message "TypeError: Trying to access 'insertBefore' property of null object" is indicating that the

Below is an example of the array I am using: var users = [ { 'id': 1, 'name': 'user name', 'age': 25, ... }, { 'id': 2, 'name': 'user name', 'age': 25, ... } ... ...

Unable to get the sublocality dropdown list to cascade properly in asp.net mvc

I am dealing with three dropdown lists. The initial action method for the City dropdown is shown below: public ActionResult Create() { List<SelectListItem> li = new List<SelectListItem>(); li.Add(new Sel ...

nested objects within a JSON structure

If you have the following scenario: var test = '{"0":"1", "2":"3"}'; it results in an object with key-value pairs 0: 1 and 2: 3 How can I create an object that looks like this: object: 0: 1 2: 3 object: 4: 5 6: 7? I've attempted the fo ...

Prevent the occurrence of the dreaded 'undefined property' error when attempting to validate a grandchild property

I need to set the state of a React component to the location.state passed with React Router. If it doesn't exist, I want to set it to 0. However, in some cases, the parent (location.state) of the property I am checking for (currentItem) doesn't ...

How can I execute a MySQL query by clicking on a link using the onclick event?

I am currently facing an issue with a PHP script. My goal is to execute a MySQL query in my PHP code when I click on a specific link. Here is the code I have: <?php function hello(){ $browser=$_SERVER['HTTP_USER_AGENT']; $url="http ...

Sending a message to an iframe from a different origin using JavaScript

Just starting out with JavaScript and I'm attempting to send a message to my iframe in order to scroll it. Here is the code I am using: scroll(i) { var src = $("#iframe").attr("src"); $("#iframe").contentWindow.postMe ...

Enclose chosen images with selection made

Below is the code snippet I am working with: <select multiple="multiple" class="image-picker show-html"> <option data-img-src="http://placehold.it/125x200" value="1">SportField 1</option> <option data-img-src="http://placehold ...

Having trouble establishing a connection with the OpenWeather API in your Javascript code

I'm trying to show the current weather conditions for the state I enter, but every time I do, it gives an error saying "wrong city name" and then shows as undefined. const button = document.querySelector('.button'); const inputValue = docume ...