Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop through an array and continue at beginning once it reaches end?

My problem:

I have an array called "weekdays":

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Imagine it is Saturday and I want to know how many days it is until Tuesday (obviously 3 days). How can I loop through the array – starting at "Sat" and continue at the beginning until it reaches "Tue"?

My code 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 = howManyDays + 1;
}

However, it seems to be that "howManyDays" is still 0 when I run the code in the console in the browser.

>Solution :

This loop seems most appropriate to the question asked. Although a bit silly if you run 2 indexOf you already got the distance. just need to substract and module array length. But this approach is good for the loop, because you can just compare the values as you go until you find "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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading