在javascript中排序天数

时间:2013-07-26 23:38:54

标签: javascript algorithm function sorting

我有一个数组。该数组可以包含1到7个唯一的日期名称字符串。当天的名字将从周一到周日。 - 例如:

  

[“星期二”,“星期四”,“太阳”]

我想使用javascript对该数组进行排序,以便订单将从今天开始。

ie:如果今天是星期五,那么排序的数组应该是

  

[“太阳”,“星期二”,“星期四”]

如果今天是星期四那么排序的数组应该是

  

[“Thu”,“Sun”,“Tue”]

有人可以帮忙吗?

9 个答案:

答案 0 :(得分:9)

function sort_days(days) {

要获取今天的某一天,请使用new Date().getDay()。这假定为Sunday = 0, Monday = 1, ..., Saturday = 6

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

(今天是星期五,所以sorted_list['Fri','Sat','Sun','Mon','Tue','Wed','Thu']

最后,要排序,请使用indexOf

    return days.sort(function(a,b) { return sorted_list.indexOf(a) > sorted_list.indexOf(b); });
}

全部放在一起:

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

答案 1 :(得分:4)

这是我提出的一个功能:

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

一般的想法是根据今天的某一天从头到尾旋转元素来重新安排一周中的几天。然后,使用该顺序重新排序输入数组以匹配。我没有实际排序,而是根据输入数组的内容过滤了daysOfWeek数组。

我不确定支持Array.filter的效果如何,因此您可能希望将其更改为通用for循环,具体取决于您要支持的浏览器。

Here's a jsfiddle你可以在那里玩它。

或者,您可以按照类似的策略使用内置的Array.sort方法:

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

here's another fiddle一起玩。

答案 2 :(得分: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"];

答案 3 :(得分:1)

万一我们曾经设法获得或失去一天,我已经建立了我不需要硬编码的日期列表:)这里希望有一天我们在星期六和星期日之间得到额外的24小时!

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

答案 4 :(得分: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])
  })
}

答案 5 :(得分:0)

如果您有一个对象数组,其中有一天作为键,您可以使用此版本的@SheetJS答案

&#13;
&#13;
    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));
&#13;
&#13;
&#13;

答案 6 :(得分:0)

这是解决问题的一种有趣方法-如果它也相当有效(即没有复杂的对象等),也不会感到惊讶

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

答案 7 :(得分:0)

我还选择了filter

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

答案 8 :(得分:0)

这是我的答案,如果您想对“星期一”开始的日期进行排序。您只需更改daySort变量值即可更改开始日期。

您只需要给此方法提供未排序的工作日数组,它将对其进行排序。

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