按日期对表格排序,带有“

时间:2018-09-04 09:19:50

标签: angular typescript sorting

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

问题在于排序没有达到我的预期。 通常,使用字符串时,会将空字符串放在排序的顶部或底部。

但是随着日期的推移,它们会被推向中间。

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

我试图使它成为某种数字。但是,仍然存在与空字符串有关的问题。 any1有解决方案吗?

2 个答案:

答案 0 :(得分:1)

您需要检查该值是否可以转换为日期/时间类型,如果不是,则返回-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。它功能更强大,您可以在传递的值中包含格式字符串,以便正确解析该字符串。

答案 1 :(得分:0)

检查是否设置了值:

 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