Home > Back-end >  Sort an array of objects by two fields one with the end time first and if the end time is same then
Sort an array of objects by two fields one with the end time first and if the end time is same then

Time:10-12

Is this the correct approach to sort data by using infinity..? tried the solution but it's not quite what I need.

data = [{
  "status": "Accepted",
  "endTime": ""
}, {
  "status": "New",
  "endTime": "Sep 16 2022, 04:18 GMT 5"
}, {
  "status": "In Progress",
  "endTime": "Sep 16 2022, 04:18 GMT 5"
}, {
  "status": "Accepted",
  "endTime": "Sep 16 2022, 04:19 GMT 5"
}, {
  "status": "Kick Off Policy Review Task",
  "endTime": "Sep 16 2022, 04:13 GMT 5"
}];

// sort based on this order
sortDSCOrder = [
  'Canceled',
  'Accepted',
  'Completed',
  'On-Hold',
  'In Progress',
  'Not Started',
  'New',
  'Kick Off General Query Task',
  'Kick Off Policy Review Task',
];

Desc sort:

data.sort((a, b) => {
  return (
    (b.endTime ? new Date(b.endTime).getTime() : Infinity) -
    (a.endTime ? new Date(a.endTime).getTime() : Infinity) ||
    this.sortDSCOrder.indexOf(a.status) -
    this.sortDSCOrder.indexOf(b.status)
  );
});

ouptput = [{
  "status": "Accepted",
  "endTime": ""
}, {
  "status": "Accepted",
  "endTime": "Sep 16 2022, 04:19 GMT 5"
}, {
  "status": "In Progress",
  "endTime": "Sep 16 2022, 04:18 GMT 5"
}, {
  "status": "New",
  "endTime": "Sep 16 2022, 04:18 GMT 5"
}, {
  "status": "Kick Off Policy Review Task",
  "endTime": "Sep 16 2022, 04:13 GMT 5"
}];

CodePudding user response:

The issue is because the logic you're using to convert the values to a date is flawed. The dates will move to the top when null due to type coercion when converted to Date objects, and when you return 1 or -1 after the comparison instead of subtracting their values. Comparing in this manner means that you don't need to coerce null/empty values to Infinity for them to appear first.

const sortDSCOrder = ["Canceled","Accepted","Completed","On-Hold","In Progress","Not Started","New","Kick Off General Query Task","Kick Off Policy Review Task",];
const data = [{status:"Accepted",endTime:""},{status:"New",endTime:"Sep 16 2022, 04:18 GMT 5"},{status:"In Progress",endTime:"Sep 16 2022, 04:18 GMT 5"},{status:"Accepted",endTime:"Sep 16 2022, 04:19 GMT 5"},{status:"Kick Off Policy Review Task",endTime:"Sep 16 2022, 04:13 GMT 5"}];

data.sort((a, b) => {
  const aDate = new Date(a.endTime);
  const bDate = new Date(b.endTime);
  const aStateIndex = sortDSCOrder.indexOf(a.status);
  const bStateIndex = sortDSCOrder.indexOf(b.status);
  return aDate < bDate ? 1 : aDate > bDate ? -1 : aStateIndex - bStateIndex;
});

console.log(data);

  • Related