CMH CMH - 8 days ago 5
Javascript Question

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?

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