[英]Sort array of object by key
所以我有這個對象數組
[
{
'1485958472927784961': {
name: 'bruno fiverr',
points: 6,
user_id: '1485958472927784961',
tweets: [Array]
},
'1414575563323420679': {
name: 'ju',
points: 7,
user_id: '1414575563323420679',
tweets: [Array]
}
}
]
我想按用戶擁有的點數對這個數組進行排序。 我正在嘗試使用帶有以下 function 的 array.sort 使其工作:
var top10 = array.sort(function(a, b) { return a.points > b.points ? 1 : -1; }).slice(0, 10);
但我得到的只是從一開始就相同的數組。 那可能嗎?
您有一個包含單個 object 的數組,您希望按屬性對其值進行排序。 為此,您需要:
array[0]
訪問外部數組中的第一個 objectObject.values
將 object 的值提取為數組(a,b) => b.points - a.points
以降序對值進行排序.slice(0,10)
獲取 10 個元素 const array = [ { '1485958472927784961': { name: 'bruno fiverr', points: 6, user_id: '1485958472927784961', tweets: [Array] }, '1414575563323420679': { name: 'ju', points: 7, user_id: '1414575563323420679', tweets: [Array] } } ]; const top10 = Object.values(array[0]).sort((a,b) => b.points - a.points).slice(0,10); console.log(top10);
最外面的數組在這里沒用。 我會將您的數據結構更改為帶有鍵值的 object:
const data = {
'1485958472927784961': {
name: 'bruno fiverr',
points: 6,
user_id: '1485958472927784961',
tweets: [],
},
'1414575563323420679': {
name: 'ju',
points: 7,
user_id: '1414575563323420679',
tweets: [],
},
};
從中您可以獲取所有成為對象數組的值,然后對其進行排序。
const data = { '1485958472927784961': { name: 'bruno fiverr', points: 6, user_id: '1485958472927784961', tweets: [] }, '1414575563323420679': { name: 'ju', points: 7, user_id: '1414575563323420679', tweets: [] } } const sorted = Object.values(data).sort(function(a, b) { return a.points > b.points? 1: -1; }).slice(0, 10); console.log(sorted)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.