如何按日期排序数组并计算离子2

问题描述 投票:3回答: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则应该首先计数,然后计数为零,最后计算所有其他记录。任何人都可以帮我解决这个问题吗?

arrays sorting ionic-framework ionic2
2个回答
4
投票

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

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语句将按count对数组进行排序。如果count相等,代码将考虑第二个属性(lastDate)。


1
投票

试试这个:

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);
© www.soinside.com 2019 - 2024. All rights reserved.