簡體   English   中英

javascript按值排序,如果值相等,則在相等的項目之間按不同的值排序

[英]javascript sorting by value, if the values are equal, sorting between equal items by a different value

我有一個對象數據,我根據它們的點對這些數據進行排序,但如果點相同,我希望最后更新的項目位於頂部。 但我無法在這里創建算法。 你能幫助我嗎 ?

我的 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
      });
}

提前感謝您的回答。

使用Array#sortDate (作為后備):

 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);

如果后面編號的項目具有該命名約定並且始終是最近更新的,請檢查項目的順序(如果點數相等):

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]);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM