我有一個物件資料,我根據它們的點對這些資料進行排序,但如果點相同,我希望最后更新的專案位于頂部。但我無法在這里創建演算法。你能幫助我嗎 ?
我的 JSON 資料
[
{
"name": "Item 1",
"point": 3,
"updatedAt": "10/06/2022 9:39"
},
{
"name": "Item 2",
"point": 4,
"updatedAt": "10/06/2022 9:45"
},
{
"name": "Item 3",
"point": 2,
"updatedAt": "10/06/2022 9:39"
},
{
"name": "Item 4",
"point": 1,
"updatedAt": "10/06/2022 9:39"
},
{
"name": "Item 5",
"point": 5,
"updatedAt": "10/06/2022 9:39"
},
{
"name": "Item 6",
"point": 2,
"updatedAt": "11/06/2022 3:05"
}
]
例如,這里第 3 項和第 6項的點是相等的,但第 3 項顯示在頂部。因為我后來添加了第 6 項。那么,如果他們的分數相等,我如何讓第 6 項高于第 3 項?
我打算這樣做,以便最后更新的內容位于頂部。
我嘗試了幾種方法,但沒有奏效,現在這是我的起始代碼。
if (sortBy === "lowtohigh") {
computedData = data.sort((a, b) => {
return a.point - b.point
});
}
if (sortBy === "hightolow") {
computedData = data.sort((a, b) => {
return b.point - a.point
});
}
提前感謝您的回答。
uj5u.com熱心網友回復:
使用Array#sortand Date(作為后備):
const arr = [
{ "name": "Item 1", "point": 3, "updatedAt": "10/06/2022 9:39" },
{ "name": "Item 2", "point": 4, "updatedAt": "10/06/2022 9:45" },
{ "name": "Item 3", "point": 2, "updatedAt": "10/06/2022 9:39" },
{ "name": "Item 4", "point": 1, "updatedAt": "10/06/2022 9:39" },
{ "name": "Item 5", "point": 5, "updatedAt": "10/06/2022 9:39" },
{ "name": "Item 6", "point": 2, "updatedAt": "11/06/2022 3:05" }
];
const res = arr.sort((a, b) =>
a.point - b.point || new Date(b.updatedAt) - new Date(a.updatedAt)
);
console.log(res);
uj5u.com熱心網友回復:
如果后面編號的專案具有該命名約定并且始終是最近更新的,請檢查專案的順序(如果點數相等):
computedData = data.sort((a, b) => {
if (a.point - b.point) return a.point - b.point; // Change this line depending on asc or desc sort.
else {
return Number(a.name.split(" ")[1]) - Number(b.name.split(" ")[1]);
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/488997.html
標籤:javascript 排序
上一篇:Pandas,多索引-使用鍵映射重新索引兩個索引級別并保持結構
下一篇:二叉搜索樹-洗掉
