如何不借助外部库按年月排序「月份+年份」格式的字符串列表?
按年份和月份排序「月份 年份」格式的字符串列表
你可以利用JavaScript原生的Array.sort()方法,配合自定义比较函数实现排序,无需依赖任何外部库。具体实现如下:
1. 定义月份映射表
先创建一个对象,把英文月份名称映射为对应的数字(1-12),方便后续比较月份顺序:
const monthMap = { January: 1, February: 2, March: 3, April: 4, May: 5, June: 6, July: 7, August: 8, September: 9, October: 10, November: 11, December: 12 };
2. 编写排序逻辑
使用Array.sort(),在比较函数中拆分每个字符串的月份和年份,先按年份排序,年份相同时再按月份排序:
const mylist = ["October 2020","December 2022","November 2020", "January 2021"]; const sortedList = mylist.sort((a, b) => { // 拆分字符串为月份和年份两部分 const [monthA, yearA] = a.split(' '); const [monthB, yearB] = b.split(' '); // 先比较年份,转成整数后做差判断顺序 const yearDiff = parseInt(yearA) - parseInt(yearB); if (yearDiff !== 0) { return yearDiff; } // 年份相同则比较月份的数字映射值 return monthMap[monthA] - monthMap[monthB]; }); console.log(sortedList); // 输出结果:["October 2020", "November 2020", "January 2021", "December 2022"]
3. 兼容大小写不一致的场景
如果列表中的月份名称存在大小写混用(比如october或OCTOBER),可以统一转换为小写(或大写)后再匹配映射表,避免匹配失败:
const monthMap = { january: 1, february: 2, march: 3, april: 4, may: 5, june: 6, july: 7, august: 8, september: 9, october: 10, november: 11, december: 12 }; const sortedList = mylist.sort((a, b) => { const [monthA, yearA] = a.trim().split(' '); const [monthB, yearB] = b.trim().split(' '); const yearDiff = parseInt(yearA) - parseInt(yearB); if (yearDiff !== 0) { return yearDiff; } return monthMap[monthA.toLowerCase()] - monthMap[monthB.toLowerCase()]; });
内容的提问来源于stack exchange,提问作者Philip Pappas
相关产品推荐
相关产品推荐

