-1

Suppose I have an array like such

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

How would I go about if I wanted to sort the array depending on the current day. Say, if today's friday, the week array will be like this

["Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"]
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Easiest way would be just to construct a new array. Slice the current array at the index for the current day until the end, and then append the days that were before the current day index to that new array – Taplar Dec 11 '20 at 15:57
  • Or append the array to itself, and then slice from current day index to current day index + 7 – Taplar Dec 11 '20 at 15:58
  • 1
    That's not sorting, it's just rotating. – Barmar Dec 11 '20 at 15:59
  • ... or calculate the index to read according to the current day. – Teemu Dec 11 '20 at 15:59
  • https://stackoverflow.com/questions/17892674/sort-array-of-days-in-javascript Please take a look at this – Satoshi Naoki Dec 11 '20 at 15:59

1 Answers1

0

You can find the start from the index of the current day and then loop to push all elements to the result array in the correct order.

const week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const res = [];
const day = "Friday";
for(let i = 0, j = week.indexOf(day); i < week.length; i++, j = (j + 1) % week.length){
  res.push(week[j]);
}
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80