Reputation: 373
For instance, if I pass a week number as 3, I would like the array to be sorted as
weekStartDayNumber = 3
weekdays = ['wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'monday', 'tuesday']
If I pass week weekStartDayNumber as 7 I want the array to be sorted as follows
weekdays = ['sunday',...'saturday']
The array needs to be sorted based on the weekStartDayNumber.
function days(weekStartDayNumber) { //logic here}
Upvotes: 0
Views: 264
Reputation: 19
let a = function SortByDay(startNum) {
let weekDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
return weekDays
.slice(startNum - 1)
.concat(weekDays
.slice(0, startNum - 1));
};
Upvotes: 1
Reputation: 12209
Use Array.slice()
:
function arrangeDays(startNum) {
let days = ['monday', 'tuesday','wednesday', 'thursday', 'friday', 'saturday', 'sunday']
let arrStart = days.slice(startNum-1)
let arrEnd = days.slice(0, startNum-1)
return arrStart.concat(arrEnd)
}
console.log(arrangeDays(3))
console.log(arrangeDays(7))
Upvotes: 0
Reputation: 1391
const weekDays = ['monday', 'tuesday','wednesday', 'thursday', 'friday', 'saturday', 'sunday']
const days = (n) =>
// Splice will take out everything from where ever you want to start until
// the end of the array and remove that part from the original. So
// weekdays only contains whatever is left. So simply add the rest
// using concat
weekDays.splice(n - 1, weekDays.length - n + 1).concat(weekDays);
Upvotes: 2
Reputation: 964
const days = (n) => [...weekdays.slice(n-1), ...weekdays.slice(0, n-1)]
This should do what you need. A nice little ES6 one-liner.
Upvotes: 1