10

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?

CMH
  • 738
  • 1
  • 11
  • 23

11 Answers11

12
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); });
}
SheetJS
  • 22,470
  • 12
  • 65
  • 75
  • 1
    Thanks for this. This seems like the most efficient way to go about it. – CMH Jul 30 '13 at 20:31
  • I just want to share that this worked well for me, but I'm sorting objects with a `dayName` member viariable that is the day of the week. All I had to do was change the last line to `return sorted_list.indexOf(a.dayName) > sorted_list.indexOf(b.dayName)` – Dan Mantyla Jan 05 '21 at 22:40
7
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"];
chris
  • 6,653
  • 6
  • 41
  • 54
  • I would like to add a fix to a potential problem as mentioned https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description. Conditions should return -1, 1 or 0 only for the comparison to work across all browsers. – Rusty Apr 11 '23 at 17:29
  • Return `return a - b;` instead of `return a < b ? 0 : 1;` – Devio__ May 18 '23 at 12:53
5

Here's a function I came up with:

function sortDays(days) {
  var daysOfWeek = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
  var today = new Date().getDay();
  for (var i=0;i<today;i++) daysOfWeek.push(daysOfWeek.shift());
  return daysOfWeek.filter(function(d) { return days.indexOf(d) >= 0; });
}

The general idea is to re-arrange the days of the week by rotating elements from the start to the end based off what day it is today. Then, you use that ordering to re-order your input array to match. Rather than actually sorting, I just filtered the daysOfWeek array based on the contents of the input array.

I'm not sure how well Array.filter is supported, so you might want to change that to a generic for loop instead depending on which browsers you want to support.

Here's a jsfiddle where you can play with it too.

Alternatively, you can just use the built-in Array.sort method following a similar strategy:

var daysOfWeek = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];

{
    var today = new Date().getDay();
    for (var i=0;i<today;i++) daysOfWeek.push(daysOfWeek.shift());
}

function daysOfWeekSorter(x,y) {
    return daysOfWeek.indexOf(x)-daysOfWeek.indexOf(y);
}

var myDays = ["Tue", "Thu", "Sun"];
myDays.sort(daysOfWeekSorter);

And here's another fiddle to play with.

IgnisErus
  • 386
  • 1
  • 5
  • Thanks for this! I just used the answer without a loop as it seemed more efficient. – CMH Jul 30 '13 at 20:31
3

I also went with a filter option.

const inOrderDays = arr => {
  const list = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
  return list.filter(each => arr.includes(each));
}
Aid19801
  • 1,175
  • 1
  • 17
  • 30
1

Just in case we ever manage to gain or lose a day, I've built mine to not require a hardcoded day list :) here's hoping some day we get an extra 24 hours between Saturday and Sunday!

function anyDayNow( dys ) {
  var ret = [], cur = new Date(), today = cur.getUTCDay(), txt;
  do { 
    txt = cur.toUTCString().split(',')[0];
    dys.indexOf(txt)!=-1 && ret.push(txt);
    cur.setUTCDate( cur.getUTCDate() + 1 ); 
  } while ( cur.getUTCDay() != today );
  return ret;
}

console.log( anyDayNow( ["Tue", "Thu", "Sun"] ) );
Pebbl
  • 34,937
  • 6
  • 62
  • 64
1

Here is a simple way by only using indexOf, splice filter and concat functions of arrays, no need to loop:

function sortMyArray(toSort) {
    var today = new Date().toUTCString().substr(0, 3), //get today as 3 letter string
        list = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"], // days list
        before = list.splice(0, list.indexOf(today)); // splice what is before today in the list

    list = list.concat(before); // concat the list with what was spliced

    return list.filter(function (item) { return toSort.indexOf(item) !== -1}); // return the sorted list with only the asked days
}

Use

console.log(sortMyArray(["Tue", "Thu", "Sun"]));
dievardump
  • 2,484
  • 17
  • 21
  • 1
    I love how this doesn't need looping or sorting, but it doesn't actually work with the order the array will be in. In the example above, order of toSort will be ["Tue", "Thu", "Sun"] to begin with. – CMH Jul 27 '13 at 18:33
  • Oh I did not see you wanted to have a sort even if the current day was not in the array. – dievardump Jul 27 '13 at 19:34
1

Here's an interesting way of solving the problem - wouldn't be suprised if this was fairly performant too (i.e. no complex objects, etc)

const sortDays = days => {
    let arr = ['', '', '', '', '', '', '']
    days.forEach(day => {
        if (day === 'Sun') arr[0] = 'Sun'
        if (day === 'Mon') arr[1] = 'Mon'
        if (day === 'Tue') arr[2] = 'Tue'
        if (day === 'Wed') arr[3] = 'Wed'
        if (day === 'Thu') arr[4] = 'Thu'
        if (day === 'Fri') arr[5] = 'Fri'
        if (day === 'Sat') arr[6] = 'Sat'
    })
    return arr.filter(str => str !== '')
}
Ed Williams
  • 2,447
  • 3
  • 15
  • 21
0
function sortDaysByToday(ds){
  var days = {Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6},
      today = new Date().getDay()

  return ds.sort(function(a,b){
    return (days[a] < today ? days[a] + 7 : days[a])
         - (days[b] < today ? days[b] + 7 : days[b])
  })
}
גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61
0

And in case you have an array of objects that has a day as a key you can use this version of @SheetJS answer

    const sortDays = (days, timezone) => {
      const dayOfWeek = 6;
      const list = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
      const sortedList = list.slice(dayOfWeek).concat(list.slice(0, dayOfWeek));
      return days.sort((a, b) => {
        if (sortedList.indexOf(a.day) > sortedList.indexOf(b.day)) return 1;
        if (sortedList.indexOf(a.day) < sortedList.indexOf(b.day)) return -1;
        return 0;
      });
    };

    const days = [
    {"_id":"Z378zCrqGM5XNbsXK","color":"#F47373","day":"Friday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"SY83MsxwEyKYrZvxx","color":"#ea5030","day":"Friday","hour":12,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"Cy4SwenuDJqsSu8Wd","color":"#5a9830","day":"Friday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"MDboigebEAokYiuJv","color":"#F47373","day":"Monday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"PzhT93JKkJSbmuLqc","color":"#5a9830","day":"Monday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"kNuPToeSoJ3j8d6wW","color":"#F47373","day":"Saturday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"44NrPF8byhktY3w4K","color":"#5a9830","day":"Saturday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"BxwYYBKPWWEodtkbs","color":"#F47373","day":"Sunday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"9kHsucTj9JZJtyxos","color":"#37D67A","day":"Sunday","hour":9,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"5fz3tAHfHARiafuBg","color":"#ea5030","day":"Sunday","hour":12,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"ZeC8Y8YLGKrK7q3g7","color":"#5a9830","day":"Sunday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"vHjA9hcfLPCp3CBQQ","color":"#F47373","day":"Thursday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"Fmd4xccrPHqDyrhRx","color":"#37D67A","day":"Thursday","hour":8,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"Zijtdb8Cv68cPBc3L","color":"#ea5030","day":"Thursday","hour":12,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"yDf5tj3NQCZXT3iWa","color":"#5a9830","day":"Thursday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"ve9vuxcb6ZkLZgfFq","color":"#F47373","day":"Tuesday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"s5mbpz9oyzjtzXwCt","color":"#0f5b30","day":"Tuesday","hour":21,"minute":23,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"aXZSoJ3cQiA9Hocwa","color":"#5a9830","day":"Tuesday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"FqqaRBPKd3RjHzQEz","color":"#F47373","day":"Wednesday","hour":7,"minute":45,"workspaceId":"6oaKfaAc7GhGYohA9"},{"_id":"e8A5LACfXYfGtacJA","color":"#5a9830","day":"Wednesday","hour":22,"minute":53,"workspaceId":"6oaKfaAc7GhGYohA9"}]
    
    console.log(sortDays(days));
Nicholas
  • 3,529
  • 2
  • 23
  • 31
0

This is my answer IF you want to sort the day beginning 'monday'. 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.

sortDays(unsortedDays) {
  let daysSort = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',
                  'satuday', 'sunday'];
  let sortedDays = [];
  daysSort.forEach((value) => {
    if (unsortedDays.includes(value)) {
      sortedDays.push(value);
    }
    });
  return sortedDays;
}
Russel Santos
  • 27
  • 1
  • 1
  • 10
0
const sortDays = (days) => {
  let sortedDays = ["", "", "", "", "", "", ""];
  const daysWeek = [
    "MONDAY",
    "TUESDAY",
    "WEDNESDAY",
    "THURSDAY",
    "FRIDAY",
    "SATURDAY",
    "SUNDAY",
  ];
  days.forEach((day) => {
    for (let i = 0; i < 7; i++)
      if (day === daysWeek[i]) sortedDays[i] = daysWeek[i];
  });
  return sortedDays.filter((str) => str !== "");
};

console.log(
  "The sorted days: ",
  sortDays(["SATURDAY", "THURSDAY", "FRIDAY", "TUESDAY"])
);
//will return : ["TUESDAY","THURSDAY","FRIDAY","SATURDAY"]
HasanRadi93
  • 17
  • 1
  • 2
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 02 '22 at 22:44