按顺序重新排列月份序列

时间:2015-12-31 10:25:48

标签: javascript arrays angularjs

我用这样的几个月填充一个数组:

var months=["March 2016","April 2016","May 2016","January 2015","February 2016"]

考虑到这一年,我怎样才能按照以下顺序重新安排月份..:

var months=["January 2015","February 2016","March 2016","April 2016","May 2016",]

我尝试排序()按字母顺序排序的月份,这是不符合逻辑的。对此问题有任何建议吗?

3 个答案:

答案 0 :(得分:3)

您可以将两者都转换为Date对象,然后使用sort

["March 2016","April 2016","May 2016","January 2015","February 2016"].sort(function(a, b) { 
     return new Date("1 " + a) - new Date("1 " + b); 
})

编辑:感谢@Hacketo指出实际上并不需要getTime()(在答案的原始版本中)。

答案 1 :(得分:1)

您可以将对象与其月份的订单值一起使用,并按年份和月份值进行排序。



var months = ["March 2016", "April 2016", "May 2016", "January 2015", "February 2016"];

months.sort(function (a, b) {
    var MONTH = { January: 0, February: 1, March: 2, April: 3, May: 4, June: 5, July: 6, August: 7, September: 8, October: 9, November: 10, December: 11 },
        aa = a.split(' '),
        bb = b.split(' ');
    return aa[1] - bb[1] || MONTH[aa[0]] - MONTH[bb[0]];
});

document.write('<pre>' + JSON.stringify(months, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用包含月份列表作为参考的数组,然后检查索引。

var months=["March 2015","April 2016","May 2016","January 2015","February 2016"];
var m = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

months.sort(function(a,b){
    var yearA = a.split(" ")[1];
    var yearB = b.split(" ")[1];
    if (yearA != yearB){ return +yearA - +yearB ;}
    return m.indexOf(a.split(" ")[0]) -  m.indexOf(b.split(" ")[0]);
});

// ["January 2015", "March 2015", "February 2016", "April 2016", "May 2016"]