如何排序?例如,我希望每周的第一天是星期一。从这个:
星期日星期一星期二星期三星期五星期五星期六
我想要这个:
星期一星期二星期三星期四星期五星期六
或者我希望我的第一天是星期五
那么输出中应该是这样:
周五星期六周二周三周三
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
})
答案 0 :(得分:5)
切片firstDayOfWeek
之前的日子,并将它们添加到数组的末尾:
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
答案 1 :(得分:2)
您可以按以下日期获得排序
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)
答案 2 :(得分:2)
您可以创建一个包含days
数组2次迭代的数组,然后使用slice
从任何索引中获取7个项目
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
代码[...days, ...days]
给出了一个包含14个元素的数组,并且可以在一周的任何一天使用。
答案 3 :(得分:1)
尝试这样
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)
答案 4 :(得分:1)
您可以使用天数并通过添加增量来调整值,然后使用7的铰刀进行排序。
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);
答案 5 :(得分:1)
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);