-1

I want to sort my arrays using this below condition

My json object:

[
  {
    "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
  }
]

I have complaintId in my json,

i need to get json object of times with complaintId which located in last, for example there are many complaintId:1 in object.

i need to get only which have complaintId in last.

My expected output:

[
  {
    "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
  }
]
Mohamed Sameer
  • 1,847
  • 18
  • 37
  • 1
    Possible duplicate of [Sort Javascript Object Array By Date](https://stackoverflow.com/questions/10123953/sort-javascript-object-array-by-date) – Serge K. Mar 05 '18 at 13:53

1 Answers1

4

You can use array#reduce and for each type of complaintId check if it doesn't time value, then update it or if the object has time value and then update the value corresponding to that 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);
Hassan Imam
  • 16,414
  • 3
  • 29
  • 41