Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

algorithm - Sort array of days in javascript

I have an array. The array can contain 1 to 7 unique strings of day names. The day names will be in order from Mon to Sun. - eg:

["Tue", "Thu", "Sun"]

I want to use javascript to sort that array so that the order will be beginning with today.

ie: if today is Friday, then the sorted array should be

["Sun", "Tue", "Thu"]

if today is Thursday then the sorted array should be

["Thu", "Sun", "Tue"]

Can anyone help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
function sort_days(days) {

To get today's day of week, use new Date().getDay(). This assumes Sunday = 0, Monday = 1, ..., Saturday = 6.

    var day_of_week = new Date().getDay();

To generate the list of the days of week, then slice the list of names:

    var list = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
    var sorted_list = list.slice(day_of_week).concat(list.slice(0,day_of_week));

(today is Friday, so sorted_list is ['Fri','Sat','Sun','Mon','Tue','Wed','Thu'])

Finally, to sort, use indexOf:

    return days.sort(function(a,b) { return sorted_list.indexOf(a) > sorted_list.indexOf(b); });
}

Putting it all together:

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); });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...