Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 947
CMH Avatar asked Jul 26 '13 23:07

CMH


People also ask

How do I sort Days in JavaScript?

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.

How do you sort an array of dates?

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.

Can you sort an array in JavaScript?

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.


1 Answers

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"];
like image 103
chris Avatar answered Oct 12 '22 14:10

chris