文章目录
本文章主要描述了使用数组排序方法 sort() ,针对日期进行排序。前往 sort() 使用方法
1 封装进行比较方法 compare
两个参数:
参数1为:
排序用的字段
;
参数2为:是否升序排序true 为升序
,false 为降序
上代码:
const compare = (attr, rev) => {
rev = (rev || typeof rev === 'undefined') ? 1 : -1;
return (a, b) => {
a = a[attr];
b = b[attr];
if (a < b) {
return rev * -1; }
if (a > b) {
return rev * 1; }
return 0;
};
};
2 实例使用
准备一个将要排序的数组,其中 time 属性为日期,作为将要比较的字段:
const arr = [
{
id: 1, time: "2022/09/09" },
{
id: 2, time: "2022/09/10" },
{
id: 3, time: "2022/09/11" },
{
id: 4, time: "2022/10/01" },
{
id: 5, time: "2022/10/02" },
{
id: 6, time: "2022/10/03" },
{
id: 7, time: "2022/01/01" },
{
id: 8, time: "2022/02/01" },
{
id: 9, time: "2022/03/01" },
];
在 sort 方法中使用封装的 compare 方法:
const DESC = arr.sort(compare("time", false)); // 降序
console.log("DESC", DESC);
const ASC = arr.sort(compare("time", true)); // 升序
console.log("ASC", ASC);