If the prompt displays 'Monday', then you can output the following days in the console: 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', and 'Sunday'

Could someone assist me with modifying my code so that the entered day is displayed at the end of all days in the console? Currently, it shows up at the top. Here is what I have tried:

JavaScript

const daysOfWeek = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
let currentDay = prompt("Enter day of week:");
while (!daysOfWeek.includes(currentDay)) {
  currentDay = prompt("Invalid day. Enter day of week:").toLowerCase();
}
let currentDayPassed = false;
const daysLeft = [];
for (let i = 0; i < daysOfWeek.length; i++) {
  if (daysOfWeek[i] === currentDay) {
    currentDayPassed = true;
  }
  if (currentDayPassed) {
    daysLeft.push(daysOfWeek[i]);
  }
}
console.log(daysLeft);

Answer №1

If you want to streamline your code, consider utilizing the indexOf function to locate the position of a specific day within an array. You can then use this information to divide the array into two portions before and after the chosen day:

const daysOfWeek = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
let currentDay = prompt("Please input a day of the week:");
let dayIndex = daysOfWeek.indexOf(currentDay);
while (dayIndex < 0) {
  currentDay = prompt("Invalid day. Please enter a valid day of the week:").toLowerCase();
  dayIndex = daysOfWeek.indexOf(currentDay);
}

let remainingDays = daysOfWeek.slice(dayIndex+1).concat(daysOfWeek.slice(0, dayIndex+1))

console.log(remainingDays);

Answer №2

If you're looking to achieve this task in a straightforward manner, consider the following solution:

let days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

// You got this part right :-)
let selectedDay = prompt("Enter day of week:").toLowerCase();
while(!days.includes(selectedDay)){
    selectedDay = prompt("Invalid day. Enter day of week:").toLowerCase();
}

// Get the index of the selected day.
const selectedDayIndex = days.indexOf(selectedDay);

// Extract elements from the beginning of the original array based on the selected day,
// and store them in the croppedDays variable.
const croppedDays = days.splice(0, selectedDayIndex + 1);

// Append the extracted days to the end of the modified array.
days = [...days, ...croppedDays];
console.log(days);

If you're uncertain about how the .splice() method works, it might be helpful to review it for better understanding.

I hope this explanation proves beneficial!

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

Tap and conceal feature on a mobile website

I seem to be facing a JavaScript challenge. On the desktop version of my website, I've managed to create a functionality where hovering over a button reveals some text, and clicking anywhere else on the site hides the text. However, I'm now stru ...

Is it possible to set a minimum width for browser resizing?

https://i.sstatic.net/0qhjT.png Looking at the image provided, I'm doing a comparison of the minimum resizable widths between my website and GitHub's. Is there a way to enforce a minimum width limit on my website similar to GitHub's? I&apo ...

What steps can I take to generate 12 random div elements using jQuery out of a pool of 30?

Currently, all the words are displaying, but I would like the script to randomly select 12 out of the 30 words var randomdivs = $("wordstyle").get().sort(function(){ return Math.round(Math.random())-0.5; }).slice(0,12) $(randomdivs).show(); The follo ...

Attempting to assign a value to the Progress Circle

Can I modify the code to incorporate a hardcoded number instead of displaying "Goals completed:" and still have the progress bar reflect the percentage? I want to hide the prompt for users to input a number and handle all updates behind the scenes. Essent ...

How can we utilize a loop to continuously sum up numbers until we reach a multiple of another number, let's say when the total is divisible by 4?

I am trying to create a function in JavaScript that will detect when a given number is not a multiple of 4. If the number is not a multiple of 4, I want to add numbers incrementally until it reaches the closest multiple of 4. Here’s what I have so far: ...

Utilizing Vue.js to add functionality for navigation buttons allowing users to move between survey questions

In my Vue.js component, I've written code to show survey questions in a mobile app for users. Here is a snippet of the code: <div class="col-12 p-0" v-for="( i, index ) in questions" :key="i"> <p cl ...

Angular: Dividing a web page with its individual controller

Exploring Angular Composition An individual new to Angular is eager to implement the concept of "composition," where the main page contains various smaller web page components. Starting off with just a Header section that binds perfectly. <html> &l ...

Populate the content within a div element with specified height and width by utilizing JavaScript and jQuery

I need help with filling a fixed height div with long text retrieved via ajax in json format. For example, if I have a div with a height of 500px and width of 300px, with a font size of 16px. Is there a javascript recursive method that can fill the data ...

Which is causing the block: the event loop or the CPU?

example: exports.products = (req, res) => { let el = 1; for (let i = 0; i < 100000000000000; i++) { el += i; } console.log(el); ... ... ... res.redirect('/'); }; If I include a loop like this in my code, which resour ...

Include the <script> tag in the HTML code for an iframe without running it

Currently, I am working on an HTML code that involves memory for an Iframe. Interestingly, whenever I use the append function, it not only executes the code but also carries out its intended task. html = $(parser.parseFromString($("#EHtml").val(), "text/h ...

The Splice function is malfunctioning due to issues with the object (the indexOf function is not recognized)

I am currently dealing with an object that looks like this: Object {val1: "Hello", val2: "", dt1: "pilo1", dt2: "pilo2", lo1: "log1"} My goal is to remove any keys within the object that have empty values (""). I attempted the following code snippet: ...

Movement and physics mechanics for players using Physi.js

As I work on a basic game using Three.js for rendering and Physijis for physics, my question can be applied to games in general. In games, players often display movement that appears disconnected from the physics engine. They can accelerate instantly and ...

Problem encountered in Python with Selenium/WebDriver: Unable to convert script into a string

I am still a beginner with selenium and I'm trying to figure out how to run a javascript function using python and then utilize the value that it returns. I've encountered an error that has me stuck. Any assistance would be greatly appreciated. H ...

Verify if a request attribute has been established using jQuery

How can I determine if an attribute is present in a request object? I have specific error scenarios where an error message needs to be sent to the client side: Here is the servlet code snippet: request.setAttribute("error", "The following term was not fo ...

After closing, the position of the qtip2 is being altered

I've successfully integrated the qtip2 with fullcalendar jQuery plugin, which are both amazing tools. However, I'm encountering an issue with the positioning of the qtip. Here's the code snippet I'm using: $(window).load(function() { ...

What is the method behind the magic of `print(*range(*b'e'))` counting from 0 to 100?

Could someone provide insight into the process by which this code generates numbers from 0 to 100? [Code] print(*range(*b'e')) [Result] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 3 ...

Matching regex only on complete strings, not on parts of strings

My goal is to dynamically add and remove strings to a textarea when values in a table are clicked. The functionality should allow users to select and deselect values in the table, with the selected values adding or removing themselves from the textarea. It ...

What is the best way to generate a new object within a function and then return it

The function performs the following steps: Retrieves an XML document through AJAX. Identifies relevant information within the document. Dynamically converts it into an object using a for loop. How can I access this generated object outside of the functi ...

Designing a versatile pop-up window with jQuery or JavaScript that functions seamlessly across all web browsers

I've encountered an issue with my code where it displays a popup message correctly in Chrome, but when testing it on Firefox and Edge, it creates a strange box at the end of the page instead. Here is the code snippet I'm referring to: var iframe ...

The getServerSideProps function in Next.js is only executed once, meaning it won't retrieve fresh data when accessed via next/router

I'm working on a Next.js application with Server-Side Rendering (SSR) where I have an async function called getServerSideProps that is exported like this: export const getServerSideProps = getGenericServerSideProps([""]); The getGenericServerSideProp ...