Sort array of days in javascript

…衆ロ難τιáo~ 提交于 2020-08-24 06:42:13

问题


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?


回答1:


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



回答2:


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.




回答3:


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"];



回答4:


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"] ) );



回答5:


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"]));



回答6:


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])
  })
}



回答7:


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));



回答8:


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 !== '')
}



回答9:


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


来源:https://stackoverflow.com/questions/17892674/sort-array-of-days-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!