【问题标题】:Sorting an array of "month numbers" from current month从当前月份对“月份数字”数组进行排序
【发布时间】:2018-06-23 16:07:34
【问题描述】:

我们有一个月份数字数组:

const months = [1,2,3,4,5,6,7,8,9,10,11,12];

我们如何从当前月份开始对这个数组进行排序?例如

const currentMonth = 9; // September

months.sort((current, next) => { 
   // ... sorting algorithm here
});

console.log(months); // Prints Array [9,8,7,6,5,4,3,2,1,12,11,10]

【问题讨论】:

    标签: javascript arrays node.js ecmascript-6 functional-programming


    【解决方案1】:

    console.log( [1,2,3,4,5,6,7,8,9,10,11,12].map(m => (12 + 9 - m) % 12 + 1)  + '' )

    【讨论】:

      【解决方案2】:

      您不需要排序,因为它已经排序(只是不是您想要的方式):

      const months = [1,2,3,4,5,6,7,8,9,10,11,12];
      const currentMonth = 9; 
      months = months
                   .slice(currentMonth)
                   .concat(months.slice(0, currentMonth))
                   .reverse();
      

      【讨论】:

      • 那是完美的,是的,你需要跳出框框思考是正确的。您的代码中有错误:months 是一个常量,因此无法修改。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-01
      • 1970-01-01
      相关资源
      最近更新 更多