按月年对数组进行排序 JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/5 17:48:17

假设我们有一个包含 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'
]

相关文章


有用资源