代码之家  ›  专栏  ›  技术社区  ›  Swoox

使用“”对日期上的表排序

  •  1
  • Swoox  · 技术社区  · 6 年前

    所以我有下面的用例,其中我在表中有日期和空字符串。

    问题是,排序并没有达到我所期望的效果。 通常,对于字符串,它会将空字符串放在排序的顶部或底部。

    但随着日期的推移,他们不得不在两者之间徘徊。

    json = ['01-01-2018', '', '04-03-2018', '03-03-2018', '', '04-03-2018', '03-03-2018'];
    this.json.sort((obj1: string, obj2: string) => {
      if (new Date(obj1) > new Date(obj2)) { return 1; }
      if (new Date(obj1) < new Date(obj2)) { return -1; }
      return 0;
    });
    

    这将导致: 01-01-2018,,03-03-2018,04-03-2018,,03-03-2018,04-03-2018 .

    下面是一个简单的堆叠:

    Stackblitz

    我试着把它变成一个数字。但空字符串的问题仍然存在。有没有解决方案可以解决这个问题?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Igor    6 年前

    您需要检查该值是否可转换为日期/时间类型,如果不可转换,则返回-1或1(取决于您希望它们位于何处)。

    json = ['01-01-2018', '', '04-03-2018', '03-03-2018', '', '04-03-2018', '03-03-2018'];
    this.json.sort((obj1: string, obj2: string) => {
      if (obj1 === obj2) { return 0; } // if they are the same then no need to convert these instances to Date types later, just return 0
      if (!obj1) { return 1; } // thruthy check
      if (!obj2) { return -1; } // thruthy check
    
      if (new Date(obj1) > new Date(obj2)) { return 1; }
      if (new Date(obj1) < new Date(obj2)) { return -1; }
      return 0;
    });
    

    stackblitz

    // Initial array
    '01-01-2018', '', '', '', '04-03-2018', '03-03-2018', '', '04-03-2018', '03-03-2018'
    
    // Sorted array
    '01-01-2018', '03-03-2018', '03-03-2018', '04-03-2018', '04-03-2018', '', '', '', ''
    

    旁注:我建议 momentjs 而不是javascript的 Date 。它的功能更强大,您可以将格式字符串与要传递的值包含在一起,以便正确解析该字符串。

        2
  •  0
  •   Jens    6 年前

    检查是否设置了值:

     sort(){
        this.json.sort((obj1: string, obj2: string) => {
          if (!obj1 ||!obj2) {return -1}
          if (new Date(obj1)> new Date(obj2)) { return 1; }
          if (new Date(obj1)< new Date(obj2)) { return -1; }
    
          return 0;
        });
      }
    

    结果:

    ,,01-01-2018,03-03-2018,03-03-2018,04-03-2018,04-03-2018