如何对 dayjs() 时间进行排序?

How can I sort dayjs() times?

我有一个像这样的对象数组:

[
 {name: 'John Smith', date: '10:30 AM'}, 
 {name: 'Jo Smith', date: '8:30 AM'}, 
 {name: 'Ela Smith', date: '1:00 PM'}, 
 {name: 'Dave Smith', date: '12:30 PM'},
 {name: 'Elton Smith', date: '10:30 PM'}
]

我想使用 dayjs() 从最早到最新对这些进行排序,这是我们在项目的其余部分中使用的,所以我必须坚持下去。

目前我正在尝试像这样使用此功能:

dayjs.extend(isSameOrBefore);
dayjs.extend(customParseFormat);

const sortTime = (users) => {
  return shifts.sort((a, b) =>
    dayjs(a.date, 'h:mm A').isSameOrBefore(dayjs(b.date, 'h:mm A')) ? 1 : -1
  );
};

我希望数组按如下方式排序:

[
 {name: 'Jo Smith', date: '8:30 AM'},
 {name: 'John Smith', date: '10:30 AM'}, 
 {name: 'Elton Smith', date: '10:30 AM'},
 {name: 'Dave Smith', date: '12:30 PM'}, 
 {name: 'Ela Smith', date: '1:00 PM'}
]

但是,由于某些奇怪的原因,它的排序方式如下:

[
 {name: 'Jo Smith', date: '8:30 AM'},
 {name: 'Ela Smith', date: '1:00 PM'},
 {name: 'John Smith', date: '10:30 AM'}, 
 {name: 'Dave Smith', date: '12:30 PM'},
 {name: 'Elton Smith', date: '10:30 AM'}, 
]

关于为什么以及如何解决这个问题的任何想法?

您可以通过将比较器函数传递给 sort 方法来实现结果,如

const arr = [
  { name: "John Smith", date: "10:30 AM" },
  { name: "Jo Smith", date: "8:30 AM" },
  { name: "Ela Smith", date: "1:00 PM" },
  { name: "Dave Smith", date: "12:30 PM" },
  { name: "Elton Smith", date: "10:30 PM" },
];

const convertTime12to24 = (time12h) => {
  let [hours, minutes, modifier] = time12h.split(/\W+/);

  if (hours === "12") hours = "00";
  if (modifier === "PM") hours = parseInt(hours, 10) + 12;

  return [hours, minutes];
};

const result = arr.sort((a, b) => {
  const [h1, m1] = convertTime12to24(a.date);
  const [h2, m2] = convertTime12to24(b.date);

  return h1 - h2 || m1 - m2;
});

console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }