创建最后一项的Javascript排序数组

问题描述 投票:-1回答:1

我想使用以下条件对数组进行排序

我的json对象:

[
  {
    "id": 1,
    "status": true,
    "time": "2018-03-05T10:24:15.000Z",
    "complaintId": 1
  },
  {
    "id": 2,
    "status": true,
    "time": null,
    "complaintId": 1
  },
  {
    "id": 3,
    "status": true,
    "time": "2018-03-05T10:53:14.000Z",
    "complaintId": 2
  },
  {
    "id": 6,
    "status": false,
    "time": "2018-03-05T11:58:45.000Z",
    "complaintId": 1
  },
  {
    "id": 7,
    "status": true,
    "time": "2018-03-05T12:11:53.000Z",
    "complaintId": 1
  },
  {
    "id": 8,
    "status": false,
    "time": "2018-03-05T13:23:13.000Z",
    "complaintId": 2
  },
  {
    "id": 9,
    "status": true,
    "time": "2018-03-05T08:17:18.000Z",
    "complaintId": 3
  },
  {
    "id": 10,
    "status": true,
    "time": "2018-03-05T12:32:08.000Z",
    "complaintId": 2
  }
]

我在json有投诉,

我需要获得最后位于的投诉ID的json对象,例如在对象中有很多complaintId:1。

我需要得到最后一个有抱怨的人。

我的预期产量:

[
  {
    "id": 7,
    "status": true,
    "time": "2018-03-05T12:11:53.000Z",
    "complaintId": 1
  },
  {
    "id": 9,
    "status": true,
    "time": "2018-03-05T08:17:18.000Z",
    "complaintId": 3
  },
  {
    "id": 10,
    "status": true,
    "time": "2018-03-05T12:32:08.000Z",
    "complaintId": 2
  }
]
javascript arrays json object
1个回答
4
投票

您可以使用array#reduce并为每种类型的complaintId检查它是否不是time值,然后更新它或者如果对象具有时间值,然后更新对应于该complaintId的值。

var data = [ { "id": 1, "status": true, "time": "2018-03-05T10:24:15.000Z", "complaintId": 1 }, { "id": 2, "status": true, "time": null, "complaintId": 1 }, { "id": 3, "status": true, "time": "2018-03-05T10:53:14.000Z", "complaintId": 2 }, { "id": 6, "status": false,"time": "2018-03-05T11:58:45.000Z", "complaintId": 1 }, { "id": 7, "status": true, "time": "2018-03-05T12:11:53.000Z", "complaintId": 1 }, { "id": 8, "status": false, "time": "2018-03-05T13:23:13.000Z", "complaintId": 2 }, { "id": 9, "status": true, "time":"2018-03-05T08:17:18.000Z", "complaintId": 3 }, { "id": 10, "status": true, "time": "2018-03-05T12:32:08.000Z", "complaintId": 2 } ],
  result = Object.values(data.reduce((r,o) => {
    if(!r[o.complaintId] || !r[o.complaintId].time || o.time)
      r[o.complaintId] = {...o};
    return r;
  },{}))
  .sort((a,b) => a.id - b.id);
console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.