我想通过它的 xp 对象对该数组进行排序:
[
["438449925949489153", {
"xp": 2
}],
["534152271443415140", {
"xp": 3
}],
["955210908794236938", {
"xp": 1
}]
]
所以它返回这个数组:
[
["955210908794236938", {
"xp": 1
}],
["438449925949489153", {
"xp": 2
}],
["534152271443415140", {
"xp": 3
}]
]
我尝试使用 sort-json npm 模块执行此操作,但它对第一个 value 进行排序而不是 xp
const sortJson = require('sort-json');
sortJson(array)
回答1
您可以只使用原生的 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort:
let data = [
["438449925949489153", {
"xp": 2
}],
["955210908794236938", {
"xp": 3
}],
["955210908794236938", {
"xp": 1
}]
];
const ascending = (a,b) => a[1].xp - b[1].xp;
const descending = (a,b) => b[1].xp - a[1].xp;
data.sort(ascending);
console.log(data)
data.sort(descending);
console.log(data)
请注意,sort
会改变原始数组:如果您不想这样做,则需要执行原始数组的 https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy。
回答2
降序排序:
arr.sort((a,b) =>{
if (a[1].xp < b[1].xp) return 1
else return -1
})
升序:
arr.sort((a,b) =>{
if (a[1].xp < b[1].xp) return -1
else return 1
})
回答3
我会建议更干净的实现:
function compare( a, b ) {
if ( a[1] < b[1]){
return -1;
}
if ( a[1] > b[1] ){
return 1;
}
return 0;
}
arr.sort( compare );
或单线:
arr.sort((a,b) => (a[1] > b[1]) ? 1 : ((b[1] > a[1]) ? -1 : 0))