簡體   English   中英

當索引是 JavaScript 中的鍵時,對 object 的嵌套數組進行排序

[英]Sort a nested array of object when index is a key in JavaScript

我正在嘗試根據關鍵時間對嵌套的對象數組進行排序。 我將索引設置為 userId 的原因是我希望稍后能夠執行 highScoreList[userId] 來獲取所選用戶信息。

[
 '587665723162626': { userId: '587665723162626', hours: 0, lastHours: 0 },
 '120156769943556': { userId: '120156769943556', hours: 0, lastHours: 0 },
 '773193626386432': { userId: '773193626386432', hours: 10, lastHours: 2 }
]
    let highScoreList = [];
    //data is inserted via another function from mongoDB and below is how I inserted into the array.
    const updateHighScoreCache = (userId, hours, lastHours) =>{
        highScoreList[userId] = { userId, hours, lastHours };
    }
            
    function compare(a, b) {
        if(a.hours > b.hours) return 1;
        if(b.hours > a.hours) return -1;
        return 0;
    }
    highScoreList.sort(compare)

我嘗試將比較 function 中的 if 語句更改為以下內容,但數組仍然沒有改變:

   if(highScoreList[a].hours > highScoreList[b].hours) return 1;
   if(highScoreList[b].hours > highScoreList[a].hours) return -1;

排序后的預期結果是:

[
 '773193626386432': { userId: '773193626386432', hours: 10, lastHours: 2 },
 '587665723162626': { userId: '587665723162626', hours: 0, lastHours: 0 },
 '120156769943556': { userId: '120156769943556', hours: 0, lastHours: 0 }
]

但我不斷得到原始數組。

頂部的數組文字不是有效的 JS 語法。 該代碼顯示您 go 錯誤的地方。

首先,您將highScoreList定義為一個數組,然后您不填充該數組,而是為其創建 object 屬性,其中:

highScoreList[userId] = { userId, hours, lastHours };

這些(非索引)屬性被典型的數組方法(例如sort )忽略。 這些方法適用於存儲在數組索引處的值。

所以改變這個:

highScoreList[userId] = { userId, hours, lastHours };

對此:

highScoreList.push({ userId, hours, lastHours });

但是,如果該結構作為普通 object(不是數組)返回給您,如下所示:

{
  '587665723162626': { userId: '587665723162626', hours: 0, lastHours: 0 },
  '120156769943556': { userId: '120156769943556', hours: 0, lastHours: 0 },
  '773193626386432': { userId: '773193626386432', hours: 10, lastHours: 2 }
}

..然后請注意,普通對象並不是真正的排序工具。 它們更好地服務於您不關心訂單的用例。 因此,如果您真的得到這樣的 object(不是數組)並且需要訂購,那么首先將 object 轉換為數組,其中:

highScoreList = Object.values(highScoreList);

...然后調用.sort

另一句話:您的compare function 將完成這項工作,但它真正完成的方式如下:

const compare = (a, b) => a.hours - b.hours;

如果你的數組是:

const highScoreList = [
 { userId: '587665723162626', hours: 0, lastHours: 0 },
 { userId: '120156769943556', hours: 0, lastHours: 0 },
 { userId: '773193626386432', hours: 10, lastHours: 2 }
];

然后這段代碼對它進行 DESC 排序:

highScoreList.sort((x,y) => y.hours - x.hours)

然后此代碼對其進行 ASC 排序:

highScoreList.sort((x,y) => x.hours - y.hours)

暫無
暫無

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

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