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 days array starting from the current date

I’ve built a simple app that prints days from an array. When you click the button, you print another day and another etc. However, when I add a starting point – the current day – I cannot loop through following days.

const days = [
  "Monday ",
  "Tuesday ",
  "Wednesday ",
  "Thursday ",
  "Friday ",
  "Saturday ",
  "Sunday ",
];

const btn = document.querySelector("#btn");

let d = new Date();
let currentDay = d.getDay();

const list = document.querySelector("#list");
let i = 0;

btn.addEventListener("click", function () {
  let newEl = document.createElement("li");

  newEl.textContent = days[currentDay];
  // this is the place where I'm stuck
  // I cannot write: days[currentDay]++

  i++;
  if (i >= days.length) i = 0;
  list.append(newEl);
});
<h2>Days of the week:</h2>
<ul id="list"></ul>
<button id="btn">Add one more day</button>

>Solution :

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

You’re using days[currentDay]. But since currentDay does not change, it won’t work


Lets go this way:

  1. After getting currentDay, set i to currentDay (this is ok since your array has the correct order, we could use indexOf aswell.

  2. Use i as index to show the date:

const days = [
  "Monday ",
  "Tuesday ",
  "Wednesday ",
  "Thursday ",
  "Friday ",
  "Saturday ",
  "Sunday ",
];

const btn = document.querySelector("#btn");

let d = new Date();
let currentDay = d.getDay();

const list = document.querySelector("#list");
let i = currentDay;

btn.addEventListener("click", function () {

  let newEl = document.createElement("li");

  newEl.textContent = days[i];

  i++;
  if (i >= days.length) i = 0;
  list.append(newEl);
});
<h2>Days of the week:</h2>
<ul id="list"></ul>
<button id="btn">Add one more day</button>
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