简体   繁体   English

从当前月份开始排序数组

[英]Sort array beginning with current month

I have an array of months and years - the month is dispalyed as a number between 1 a 12. I want to sort the array so I can displAy the current month of the current year first. 我有几个月和几年的数组 - 月份显示为1到12之间的数字。我想对数组进行排序,以便我可以先显示当前年份的当前月份。

allMonths = [month: 1 year: 2013 value: 25, 
      month: 1 year: 2014 value: 17,
      month: 2 year: 2013 value: 10,
      month: 2 year: 2014 value: 16,
      month: 3 year: 2013 value: 25, 
      month: 3 year: 2014 value: 17,
      month: 4 year: 2013 value: 10,
      month: 4 year: 2014 value: 16,
      ......etc ]

allMonths.sort(function(a, b){
if (a.year > b.year) 
     return 1;               
if (a.month < b.month) 
     return -1;
}) 

I want the output to show the past 12 months starting at the current month with it's value (I don't need to display the year)... 我希望输出显示从当月开始的过去12个月的价值(我不需要显示年份)...

4: 16 (Apr 2014)
3 : 17(March 2014)
2: 16 (Feb  2014)
1: 16 (Jan 2014)
12 : 17(Dec 2013)
11: 16 (Nov 2013)
...etc

I haven't had much experience sorting arrays so i'm a bit lost 我没有太多排序数组的经验,所以我有点迷失

If the years are the same, return the difference between the months, otherwise return the difference between the years itself. 如果年份相同,则返回月份之间的差异,否则返回年份之间的差异。

allMonths.sort(function(a, b) {
    if (a.year === b.year) {
        return a.month - b.month;
    }
    return a.year - b.year;
});

If you want to sort the array in the descending order (most recent things first), just swap the order in which the years and months are compared, like this 如果你想按降序对数组进行排序(最近的事情是先排序),只需交换比较年份和月份的顺序,就像这样

allMonths.sort(function(a, b) {
    if (a.year === b.year) {
        return b.month - a.month;
    }
    return b.year - a.year;
});

It can be written succinctly with ternary expression, like this 它可以用三元表达式简洁地书写,就像这样

allMonths.sort(function(a, b) {
    return a.year === b.year ? b.month - a.month : b.year - a.year;
});

Note: JavaScript's sort is not guaranteed to be stable. 注意: JavaScript的排序不保证稳定。

Have a look at Sorting in JavaScript: Should every compare function have a "return 0" statement? 看看JavaScript中的排序:每个比较函数都应该有一个“返回0”语句吗? . Also notice that when the year/month is not greater than the other, it still might be smaller, which needs to take precedence over the further ordering. 另请注意,当年/月不大于另一年时,它仍然可能更小,这需要优先于进一步的排序。 Try 尝试

allMonths.sort(function(a, b) {
    if (a.year > b.year)
         return 1;
    if (a.year < b.year)
         return -1;
    if (a.month > b.month)
         return 1;
    if (a.month < b.month)
         return -1;
    return 0;
})

A shorter way to write a numeric comparison function would be 编写数字比较函数的更简单方法是

allMonths.sort(function(a, b) {
    return a.year-b.year || a.month-b.month;
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM