I have a string that contains a day of the week (ex "Monday"). I need to figure out how to take this string and get the previous day of the week.
For example if the string contains "Monday" the new string should output "Sunday".
I feel like there is a simple solution (that isn't 7 IF statements) that I'm missing here.
Try
let yesterday = {
'Monday': 'Sunday',
'Tuesday': 'Monday',
'Wednesday': 'Tuesday',
'Thursday': 'Wednesday',
'Friday': 'Thursday',
'Saturday': 'Friday',
'Sunday': 'Saturday',
}
console.log(yesterday['Monday']);
One straightforward approach, assuming correct input, would be using arrays:
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
previousDay = days[(days.indexOf(currentDay)-1+7)%7];
You can use indexOf
and return Sun
when you exceed array range:
let currentDay = "Mon";
let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
let prevDay = days[days.indexOf(currentDay) - 1 ] || "Sun";
console.log(prevDay);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With