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?
You can just change the start day by changing the daySort variable value. You just had to give this method the unsorted weekday array and it will sort it.
To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.
JavaScript Array sort()The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With