Sort array of days in javascript
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 ? 0 : 1;
};
const myArrayOfDays = ["Tuesday", "Saturday", "Monday", "Thursday"].sort(sortDays);
// returns ["Monday", "Tuesday", "Thursday", "Saturday"];
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); });
}