从当前月份排序“月份数”数组

时间:2018-01-15 01:48:42

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

我们有一系列月份数字:

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

我们如何从当前月份对此数组进行排序? e.g。

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]

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:2)

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