我有一个对象
data{
{IsOpen: true, Day: "Monday", Desc: "09:00 AM-5:00 PM"}
{IsOpen: true, Day: "Sunday", Desc: "09:00 AM-11:30 PM"}
{IsOpen: true, Day: "Wednesday", Desc: "09:00 AM-5:00 PM"}
{IsOpen: true, Day: "Friday", Desc: "09:00 AM-5:00 PM"}
{IsOpen: true, Day: "Tuesday", Desc: "09:00 AM-5:00 PM"}
{IsOpen: true, Day: "Thursday", Desc: "09:00 AM-5:00 PM"}
{IsOpen: true, Day: "Saturday", Desc: "09:00 AM-5:00 PM"}
}
现在,我希望此排序按星期名称升序排列,但我认为我需要更多的是排序顺序应以今天的日期名称开头。
例如,如果今天是星期五,那么应该是 1星期五 2星期六 3星期日 4日星期一 5星期二 6星期三 星期四7
答案 0 :(得分:1)
如果日期值小于所需的开始日期,则可以使用先前的检查进行排序。
function sort(array, firstDay) {
var order = { Monday: 1, Tuesday: 2, Wednesday: 3, Thursday: 4, Friday: 5, Saturday: 6, Sunday: 7 },
first = order[firstDay];
return array.sort(({ Day: a }, { Day: b }) =>
(order[a] < first) - (order[b] < first) || order[a] - order[b]);
}
var data = [{ IsOpen: true, Day: "Monday", Desc: "09:00 AM-5:00 PM" }, { IsOpen: true, Day: "Sunday", Desc: "09:00 AM-11:30 PM" }, { IsOpen: true, Day: "Wednesday", Desc: "09:00 AM-5:00 PM" }, { IsOpen: true, Day: "Friday", Desc: "09:00 AM-5:00 PM" }, { IsOpen: true, Day: "Tuesday", Desc: "09:00 AM-5:00 PM" }, { IsOpen: true, Day: "Thursday", Desc: "09:00 AM-5:00 PM" }, { IsOpen: true, Day: "Saturday", Desc: "09:00 AM-5:00 PM" }];
console.log(sort(data, 'Friday'));
console.log(sort(data, 'Monday'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
创建日期名称数组,并使用...
获取一周中今天的索引。然后通过将今天之前的天移动到数组结尾来相应地调整日期名称数组
最后通过比较调整后的日期名称数组中每个对象的new Date().getDay()
的索引对数据进行排序
Day
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
todayIndex = new Date().getDay();// returns 0-6
// move days before today to end of array
days = days.concat(days.splice(0, todayIndex));
// sort by index in days array
data.sort((a, b) => days.indexOf(a.Day) - days.indexOf(b.Day));
console.log('Days:', JSON.stringify(days))
console.log('Data:', data)