I want to display the entered day
in the prompt at the last
after all days in the console as mentioned above in the question above. So far I have tried this logic but still the entered day is displaying at the top
instead of at the end
. If someone can please help me in rectifying my code
JS
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);
CodePudding user response:
You can simplify your code by using indexOf
to find the index of the day in the array and then using that value to slice the array before and after the selected day:
const daysOfWeek = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
let currentDay = prompt("Enter day of week:");
let dayNum = daysOfWeek.indexOf(currentDay);
while (dayNum < 0) {
currentDay = prompt("Invalid day. Enter day of week:").toLowerCase();
dayNum = daysOfWeek.indexOf(currentDay);
}
let daysLeft = daysOfWeek.slice(dayNum 1).concat(daysOfWeek.slice(0, dayNum 1))
console.log(daysLeft);
CodePudding user response:
You could do this quite simply like:
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();
}
// Retrieve the index of the selected day.
const selectedDayIndex = days.indexOf(selectedDay);
// Crop that amount of elements from the start of the original array, and store
// the cropped elements inside of the croppedDays variable.
const croppedDays = days.splice(0, selectedDayIndex 1);
// Add the cropped days to the end of the spliced array.
days = [...days, ...croppedDays];
console.log(days);
It might be worth reading up on the .splice()
method if you're not quite sure how it works.
Hope this helps!