所以我有這個物件陣列
[
{
'1485958472927784961': {
name: 'bruno fiverr',
points: 6,
user_id: '1485958472927784961',
tweets: [Array]
},
'1414575563323420679': {
name: 'ju',
points: 7,
user_id: '1414575563323420679',
tweets: [Array]
}
}
]
我想按用戶擁有的點數對這個陣列進行排序。我正在嘗試使用具有以下功能的 array.sort 使其作業:
var top10 = array.sort(function(a, b) { return a.points > b.points ? 1 : -1; }).slice(0, 10);
但我得到的只是從一開始就相同的陣列。那可能嗎?
uj5u.com熱心網友回復:
您有一個包含單個物件的陣列,您希望按屬性對其值進行排序。為此,您需要:
- 訪問外部陣列中的第一個物件
array[0] - 將物件的值提取為陣列
Object.values - 使用 sort 函式按降序對值進行排序
(a,b) => b.points - a.points - 獲得你的 10 個元素
.slice(0,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);
uj5u.com熱心網友回復:
最外面的陣列在這里沒用。我會將您的資料結構更改為具有鍵值的物件:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/421444.html
標籤:
