按月JavaScript排序数组
假设我们有一个数组,其中包含MM-YYYY格式的日期,如下所示:
const arr = ["1-2016", "7-2015", "7-2016", "3-2016", "8-2016", "2-2016", "6-2016", "8-2015", "5-2016", "4-2016", "9-2015", "10-2015", "11-2015", "12-2015"];
我们需要编写一个JavaScript函数,该函数接受一个这样的数组并对其进行排序,以使数组中的日期以从最早到最新的顺序排列。
示例
为此的代码将是-
const arr = ["1-2016", "7-2015", "7-2016", "3-2016", "8-2016", "2-2016", "6-2016", "8-2015", "5-2016", "4-2016", "9-2015", "10-2015", "11-2015", "12-2015"];
const padToString = (num) => {
return String("0" + num).slice(-2);
};
const sortByDate = (first, second) => {
const firstPart = first.split('-'), secondPart = second.split('-');
const a = firstPart[1]+padToString(firstPart[0]);
const b = secondPart[1]+padToString(secondPart[0]);
return a - b;
};
arr.sort(sortByDate);
console.log(arr);输出结果
控制台中的输出将是-
[ '7-2015', '8-2015', '9-2015', '10-2015', '11-2015', '12-2015', '1-2016', '2-2016', '3-2016', '4-2016', '5-2016', '6-2016', '7-2016', '8-2016' ]
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短