Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  186] [ 1]  / answers: 1 / hits: 15611  / 11 Years ago, fri, july 26, 2013, 12:00:00

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?


More From » algorithm

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

[#76711] Thursday, July 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchell

Total Points: 95
Total Questions: 110
Total Answers: 87

Location: Gabon
Member since Thu, Jul 15, 2021
3 Years ago
mitchell questions
;