排序月份名称

时间:2014-12-22 09:11:08

标签: jquery

使用jQuery

按顺序对月份名称进行排序

输入

month = [ "Apr","May","Jun","Oct","Nov","Dec","Jul","Aug","Sep"];

预期输出

month = [ "Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

如何对月份名称进行排序? sort() 只能缩短字母,字母数字或数字值。

2 个答案:

答案 0 :(得分:9)

获取一年中所有月份的数组,这些月份的顺序正确(硬编码以供参考)并使用主月数组的索引作为sort()

中的排序条件
var allMonths = ['Jan','Feb','Mar', 'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

var month = [ "Apr","May","Jun","Oct","Nov","Dec","Jul","Aug","Sep"];

month.sort(function(a,b){
    return allMonths.indexOf(a) > allMonths.indexOf(b);
});

// returns  ["Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

DEMO

答案 1 :(得分:2)

就我而言,我需要按照 Chance Smith 在已接受答案的评论中的建议稍微调整 RTF 的答案以使其正常工作。修改是将 '>' 更改为 '-'。我正在这里粘贴工作代码,以防有人需要。

var allMonths = ['Jan','Feb','Mar', 'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

var month = [ "Apr","May","Jun","Oct","Nov","Dec","Jul","Aug","Sep"];

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

// returns  ["Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]