gpt4 book ai didi

javascript - 根据当前日期排序数组

转载 作者:行者123 更新时间:2023-11-30 11:45:59 25 4
gpt4 key购买 nike

我正在尝试根据今天的日期对下面的数组重新排序:

[
{
"index": "0",
"day": "Monday",
"food": "Salad"
},
{
"index": "1",
"day": "Friday",
"food": "Pasta"
},
{
"index": "2",
"day": "Sunday",
"food": "Pasta"
},
{
"index": "3",
"day": "Thursday",
"food": "Pasta"
},
{
"index": "4",
"day": "Tuesday",
"food": "Pasta"
},
{
"index": "2",
"day": "Sunday",
"food": "Pasta"
},
{
"index": "5",
"day": "Wednesday",
"food": "Pasta"
},
{
"index": "6",
"day": "Saturday",
"food": "Pasta"
}
]

假设今天是星期六,排序后,项目索引的预期输出为:6, 2, 2, 0, 4, 5, 3, 1如果今天是 星期二,则按索引输出为:4, 5, 3, 1, 6, 2, 2, 0

我正在使用 moment.js,到目前为止我还没有为此创建一个不庞大的代码。最后,我想将代码包装在自定义 orderBy 过滤器中,以用于 ng-repeat 指令。

最佳答案

这是我想出的最小解决方案:

const DAYS = { 'Sunday': 0, 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6 };

// Get the relative index of a day using today as a reference.
function relativeIndex(day) {
const TODAY = new Date().getDay();
return (DAYS[day] - TODAY + 7) % 7;
}

// Sort a lit of data starting by today.
function sort(data) {
return data.sort((a, b) => relativeIndex(a.day) - relativeIndex(b.day));
}

这里的关键是 relativeIndex 函数,它使用今天作为引用来计算任何一天的指数。

关于javascript - 根据当前日期排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40954830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com