按月年对数组进行排序 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' ]
广告