1
votes

How to sort this? For example i want that my first day of week will be Monday. From this:

Sun Mon Tue Wed Thu Fri Sat

i want this:

Mon Tue Wed Thu Fri Sat Sun

or i want that my first day of week will be Friday

then in output should be this:

Fri Sat Sun Mon Tue Wed Thu

let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] //by default first day of week is 0
let firstDayOfWeek = 1 //Mon

days = days.map(m=>{
  //how i can sort this?
  return m
})
6

6 Answers

2
votes

You can get sorted days by

let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] //by default first day of week is 0
let firstDayOfWeek = 2 //Mon

let sorted = days.map((_, i) => days[(i+firstDayOfWeek)%7]);

console.log(sorted)
5
votes

Slice the days before firstDayOfWeek, and add them to the end of the array:

const orderByFirstDayOfWeek = (firstDayOfWeek, days) =>
  [...days.slice(firstDayOfWeek), ...days.slice(0, firstDayOfWeek)]

const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] //by default first day of week is 0

console.log(JSON.stringify(orderByFirstDayOfWeek(1, days))) // Mon 1st
console.log(JSON.stringify(orderByFirstDayOfWeek(5, days))) // Fri 1st
2
votes

You could create an array with 2 iterations of days array and then use slice to get 7 items from any index

let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

function getSortedWeek(firstDayOfWeek, days) {
  return [...days, ...days].slice(firstDayOfWeek, firstDayOfWeek + 7)
}

console.log(getSortedWeek(1, days)) // Mon
console.log(getSortedWeek(3, days)) // Wed

The code [...days, ...days] gives an array with 14 elements and will work for any day of the week.

1
votes

You could take a day number and adjust the value by adding the delta and take the reaminder with seven for sorting.

const
    dayValues = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 },
    days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    firstDayOfWeek = 1,
    delta = 7 - firstDayOfWeek;

days.sort((a, b) => (dayValues[a] + delta) % 7 - (dayValues[b] + delta) % 7);

console.log(days);
1
votes

Try like this

let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] //by 
function sortDay(firstDayOfWeek){
  var result = [];
  for(i=0; i<days.length;i++){
    result.push(days[firstDayOfWeek%7])
    firstDayOfWeek++;
  }
  console.log(JSON.stringify(result))
}
sortDay(1)
sortDay(4)
1
votes

let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] //by default first day of week is 0
let firstDayOfWeek = 2 //Mon

days = days.slice(firstDayOfWeek).concat(days.slice(0, firstDayOfWeek));

console.log(days);