[英]How to sort an array of objects in the same order as an id array
我有一個這樣的玩家對象數組:
var players = [{
id: "thisIsID1",
name: "William",
otherProps
},
{
id: "thisIsID2",
name: "Shakespeare",
otherProps
},
{
id: "thisIsID3",
name: "Lola",
otherProps
}]
我有他們的 ID 數組已經被洗牌,就像這樣:
var shuffledIDs = ["thisIsID2", "thisIsID3", "thisIsID1"]
如何對players
var 進行排序,以便對象與shuffledIDs
的相應 ID 的順序相同?
編輯:不同的名字只是為了讓玩家不同
如果您的數據很短,那么您可以使用以下單行對其進行排序:
players = shuffledIDs.map(id => players.find(v => v.id == id))
本質上,對於shuffledID
中的每個 id,它會在具有該 id 的players
中找到元素並將其放在正確的位置。 但是,這需要 O(n^2) 時間,因此它可能無法很好地擴展到更大的數據。 如果您想要更快的方法,您可以維護一個 object 的 ID:
var ids = {};
players.forEach(v => ids[v.id] = v);
players = shuffledIDs.map(v => ids[v]);
您可以使用數組.find()
方法來實現它:
var players = [{ id: "thisIsID1", name: "William" }, { id: "thisIsID2", name: "Shakespeare" }, { id: "thisIsID3", name: "Lola" }] var shuffledIDs = ["thisIsID2", "thisIsID3", "thisIsID1"] var result = shuffledIDs.map(x => players.find(p=>p.id === x)) console.log(result)
使用鍵和值作為隨機數組的索引創建 object。 使用sort
方法並優先排序高於洗牌索引的鹼基。 這種方式甚至應該在玩家重復數據的情況下。
var players = [ { id: "thisIsID1", name: "William" }, { id: "thisIsID2", name: "Shakespeare" }, { id: "thisIsID3", name: "Lola" } ]; const shuffleIds = ["thisIsID2", "thisIsID3", "thisIsID1"]; const shuf_idx = Object.fromEntries(shuffleIds.map((x, i) => [x, i])); players.sort((a, b) => shuf_idx[a.id] - shuf_idx[b.id]); console.log(players);
const shuffledIDs = ["thisIsID2", "thisIsID3", "thisIsID1"]; const players = [{ id: "thisIsID1", name: "William" }, { id: "thisIsID2", name: "Shakespeare" }, { id: "thisIsID3", name: "Lola" }]; const result = players.map((e, i) => players.find(f => f.id === shuffledIDs[i])); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.