【JS】使用数组方法 sort 排序,根据日期大小完成数组排序

本文章主要描述了使用数组排序方法 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);

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_53931766/article/details/126782508