我有一个数组。该数组可以包含 1 到 7 个唯一的日期名称字符串。日期名称将按周一到周日的顺序排列。 - 例如:
[“星期二”、“星期四”、“太阳”]
我想使用javascript对该数组进行排序,以便顺序从今天开始。
即:如果今天是星期五,那么排序后的数组应该是
[“周日”、“周二”、“周四”]
如果今天是星期四,那么排序后的数组应该是
[“周四”、“周日”、“周二”]
有人可以帮忙吗?
function sort_days(days) {
要获取今天是星期几,请使用
new Date().getDay()
。这假设 Sunday = 0, Monday = 1, ..., Saturday = 6
。
var day_of_week = new Date().getDay();
要生成星期几的列表,然后对名称列表进行切片:
var list = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
var sorted_list = list.slice(day_of_week).concat(list.slice(0,day_of_week));
(今天是星期五,所以
sorted_list
是['Fri','Sat','Sun','Mon','Tue','Wed','Thu']
)
最后,要排序,请使用
indexOf
:
return days.sort(function(a,b) { return sorted_list.indexOf(a) > sorted_list.indexOf(b); });
}
把它们放在一起:
function sort_days(days) {
var day_of_week = new Date().getDay();
var list = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
var sorted_list = list.slice(day_of_week).concat(list.slice(0,day_of_week));
return days.sort(function(a,b) { return sorted_list.indexOf(a) > sorted_list.indexOf(b); });
}
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const sortDays = function (a, b) {
a = days.indexOf(a);
b = days.indexOf(b);
return a - b;
};
const myArrayOfDays = ["Tuesday", "Saturday", "Monday", "Thursday"].sort(sortDays);
// returns ["Monday", "Tuesday", "Thursday", "Saturday"];
这是我想出的一个函数:
function sortDays(days) {
var daysOfWeek = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
var today = new Date().getDay();
for (var i=0;i<today;i++) daysOfWeek.push(daysOfWeek.shift());
return daysOfWeek.filter(function(d) { return days.indexOf(d) >= 0; });
}
总体思路是根据今天的日期从开始到结束旋转元素来重新排列一周中的日子。然后,您使用该顺序对输入数组重新排序以匹配。我只是根据输入数组的内容过滤了
daysOfWeek
数组,而不是实际排序。
我不确定
Array.filter
的支持程度如何,因此您可能需要将其更改为通用 for 循环,而不是取决于您想要支持的浏览器。
这里有一个jsfiddle,你也可以用它来玩。
或者,您可以按照类似的策略使用内置的
Array.sort
方法:
var daysOfWeek = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
{
var today = new Date().getDay();
for (var i=0;i<today;i++) daysOfWeek.push(daysOfWeek.shift());
}
function daysOfWeekSorter(x,y) {
return daysOfWeek.indexOf(x)-daysOfWeek.indexOf(y);
}
var myDays = ["Tue", "Thu", "Sun"];
myDays.sort(daysOfWeekSorter);
还有这是另一个可以玩的小提琴。
我还选择了
filter
选项。
const inOrderDays = arr => {
const list = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
return list.filter(each => arr.includes(each));
}
以防万一我们能够增加或减少一天,我已经构建了我的一天,不需要硬编码的日期列表:)希望有一天我们能在周六和周日之间获得额外的 24 小时!
function anyDayNow( dys ) {
var ret = [], cur = new Date(), today = cur.getUTCDay(), txt;
do {
txt = cur.toUTCString().split(',')[0];
dys.indexOf(txt)!=-1 && ret.push(txt);
cur.setUTCDate( cur.getUTCDate() + 1 );
} while ( cur.getUTCDay() != today );
return ret;
}
console.log( anyDayNow( ["Tue", "Thu", "Sun"] ) );
这里有一个简单的方法,只使用数组的indexOf、splice filter和concat函数,不需要循环:
function sortMyArray(toSort) {
var today = new Date().toUTCString().substr(0, 3), //get today as 3 letter string
list = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"], // days list
before = list.splice(0, list.indexOf(today)); // splice what is before today in the list
list = list.concat(before); // concat the list with what was spliced
return list.filter(function (item) { return toSort.indexOf(item) !== -1}); // return the sorted list with only the asked days
}
使用
console.log(sortMyArray(["Tue", "Thu", "Sun"]));
这是解决问题的一种有趣的方法 - 如果这也相当高效(即没有复杂的对象等),就不会感到惊讶
const sortDays = days => {
let arr = ['', '', '', '', '', '', '']
days.forEach(day => {
if (day === 'Sun') arr[0] = 'Sun'
if (day === 'Mon') arr[1] = 'Mon'
if (day === 'Tue') arr[2] = 'Tue'
if (day === 'Wed') arr[3] = 'Wed'
if (day === 'Thu') arr[4] = 'Thu'
if (day === 'Fri') arr[5] = 'Fri'
if (day === 'Sat') arr[6] = 'Sat'
})
return arr.filter(str => str !== '')
}
function sortDaysByToday(ds){
var days = {Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6},
today = new Date().getDay()
return ds.sort(function(a,b){
return (days[a] < today ? days[a] + 7 : days[a])
- (days[b] < today ? days[b] + 7 : days[b])
})
}
如果您有一个以一天为键的对象数组,您可以使用此版本的 @SheetJS 答案
const sortDays = (days, timezone) => {
const dayOfWeek = 6;
const list = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const sortedList = list.slice(dayOfWeek).concat(list.slice(0, dayOfWeek));
return days.sort((a, b) => {
if (sortedList.indexOf(a.day) > sortedList.indexOf(b.day)) return 1;
if (sortedList.indexOf(a.day) < sortedList.indexOf(b.day)) return -1;
return 0;
});
};
const days = [
{"_id":"Z378zCrqGM5XNbsXK","color":"#F47373","day":"Friday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"SY83MsxwEyKYrZvxx","color":"#ea5030","day":"Friday","hour":12,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"Cy4SwenuDJqsSu8Wd","color":"#5a9830","day":"Friday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"MDboigebEAokYiuJv","color":"#F47373","day":"Monday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"PzhT93JKkJSbmuLqc","color":"#5a9830","day":"Monday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"kNuPToeSoJ3j8d6wW","color":"#F47373","day":"Saturday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"44NrPF8byhktY3w4K","color":"#5a9830","day":"Saturday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"BxwYYBKPWWEodtkbs","color":"#F47373","day":"Sunday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"9kHsucTj9JZJtyxos","color":"#37D67A","day":"Sunday","hour":9,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"5fz3tAHfHARiafuBg","color":"#ea5030","day":"Sunday","hour":12,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"ZeC8Y8YLGKrK7q3g7","color":"#5a9830","day":"Sunday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"vHjA9hcfLPCp3CBQQ","color":"#F47373","day":"Thursday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"Fmd4xccrPHqDyrhRx","color":"#37D67A","day":"Thursday","hour":8,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"Zijtdb8Cv68cPBc3L","color":"#ea5030","day":"Thursday","hour":12,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"yDf5tj3NQCZXT3iWa","color":"#5a9830","day":"Thursday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"ve9vuxcb6ZkLZgfFq","color":"#F47373","day":"Tuesday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"s5mbpz9oyzjtzXwCt","color":"#0f5b30","day":"Tuesday","hour":21,"minute":23,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"aXZSoJ3cQiA9Hocwa","color":"#5a9830","day":"Tuesday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"FqqaRBPKd3RjHzQEz","color":"#F47373","day":"Wednesday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"e8A5LACfXYfGtacJA","color":"#5a9830","day":"Wednesday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"}]
console.log(sortDays(days));
如果您想对从“星期一”开始的日期进行排序,这就是我的答案。您只需更改
变量值即可更改开始日期。daySort
您只需为该方法提供未排序的工作日数组,它就会对其进行排序。
sortDays(unsortedDays) {
let daysSort = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',
'satuday', 'sunday'];
let sortedDays = [];
daysSort.forEach((value) => {
if (unsortedDays.includes(value)) {
sortedDays.push(value);
}
});
return sortedDays;
}
const sortDays = (days) => {
let sortedDays = ["", "", "", "", "", "", ""];
const daysWeek = [
"MONDAY",
"TUESDAY",
"WEDNESDAY",
"THURSDAY",
"FRIDAY",
"SATURDAY",
"SUNDAY",
];
days.forEach((day) => {
for (let i = 0; i < 7; i++)
if (day === daysWeek[i]) sortedDays[i] = daysWeek[i];
});
return sortedDays.filter((str) => str !== "");
};
console.log(
"The sorted days: ",
sortDays(["SATURDAY", "THURSDAY", "FRIDAY", "TUESDAY"])
);
//will return : ["TUESDAY","THURSDAY","FRIDAY","SATURDAY"]