[英]Sort array with Objects inside of Objects
我有這個數組:
[
["name1", { count: 20 }],
["name2", { count: 10 }]
]
我將如何根據計數值對這個數組進行排序?
我曾嘗試使用排序功能,
const sort = Array.sort((a, b) => b.count - a.count);
但這並沒有改變任何事情。
您需要訪問外部數組內的數組中的第二個條目。 您的代碼在數組條目上使用count
,但它們沒有count
屬性:
theArray.sort((a, b) => b[1].count - a[1].count);
另請注意,您對實際數組而不是Array
構造函數調用sort
。 它還對數組進行就地排序,而不是返回已排序的數組(不過,它還返回您調用它的數組)。
現場示例:
const theArray = [ ["name1", { count: 20 }], ["name2", { count: 10 }], ["name3", { count: 15 }] ]; console.log("before:", theArray); theArray.sort((a, b) => b[1].count - a[1].count); console.log("after:", theArray);
.as-console-wrapper { max-height: 100% !important; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.