如何按日期对数组进行排序并在 ionic 2 中进行计数

how to sort array by date and count in ionic 2

我想按日期和计数对数组进行排序,我只能按日期对数组进行排序我的数据如下

   count    date
    "0"     "2018-03-06T07:09:02+00:00"
    "0"     "2018-03-06T07:07:02+00:00"
    "0"     "2018-03-06T07:06:03+00:00"
    "0"     "2018-03-06T07:02:06+00:00"
    "0"     "2018-03-06T06:39:55+00:00"
    "0"     "2018-03-06T06:30:14+00:00"
    "1"     "2018-03-06T06:22:20+00:00"
    "1"     "2018-03-06T06:07:04+00:00"
    "0"     "2018-03-06T06:03:17+00:00"
    "14"    "2018-03-01T10:28:27.998000+00:00"
    "0"     null
    "0"     null
    "0"     null

我的代码如下..

this.nodelist.sort((a, b) => {//lastDate dsc

      if (new Date(b.lastDate) > new Date(a.lastDate)) {
        return 1;
      }
      if (new Date(b.lastDate) < new Date(a.lastDate)) {
        return -1;
      }

      return 0;
    });

我想按计数和日期对数组进行排序,这意味着如果数组的计数 > 0,那么它应该首先计数,然后计数为零,最后是所有其他记录。谁能帮我解决这个问题?

您可以使用您的代码并像这样修改它:

this.nodelist.sort((a, b) => {
    // 1st property, sort by count
    if (a.count > b.count)
        return -1;

    if (a.count < b.count)
        return 1;

    // 2nd property, sort by date
    if (new Date(b.lastDate) > new Date(a.lastDate))
        return 1;

    if (new Date(b.lastDate) < new Date(a.lastDate))
        return -1;

    return 0;
});

它是如何工作的? 前两个 if 语句将按计数对数组进行排序。 如果计数相等,代码将考虑第二个 属性 (lastDate).

试试这个:

let xyz = numbers.sort(function(a, b) {
  var countA = a.count;
  var countB = b.count;
  var dateA = new Date(a.date);
  var dateB = new Date(b.date);

  if(countA == countB)
  {
      return (dateB < dateA) ? -1 : (dateB > dateA) ? 1 : 0;
  }
  else
  {
      return (countB < countA) ? -1 : 1;
  }

});

console.log(xyz);