我有一個這樣的物件陣列:
我有一個這樣的物件陣列。
[
{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'/span>)。 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'}。
]
對于為什么以及如何解決這個問題,有什么想法嗎?
uj5u.com熱心網友回復:
你可以通過將比較器函式傳遞給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"/span>) hours = "00"/span>;
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. 它只是為了給輸出填充高度。所以請忽略它 */
.as-console-wrapper { max-height: 100% ! important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/310855.html
標籤:
上一篇:Pandas對列進行求和,直到>=sum(values),然后將df左邊的專案分割到dfNEW中。
下一篇:PHP關聯陣列計數和提取
