我的 json 看起来像这样:
[
{
"cash": 100,
"uid": "LHy2qRGaf3nkWQgU4axO",
"name": "test2"
},
{
"cash": 1000000,
"uid": "01wFhCSlnd9vSDY4NIkx",
"name": "test"
},
{
"cash": 500,
"uid": "PBOhla0jPwI4PIeNmmPg",
"name": "test3"
}
]
我正在尝试按用户现金对 json 进行排序。 所以我所做的是:
var objArr = []; // the json array
function compare(a, b) {
console.log("a" + a.cash);
console.log("b" + b.cash);
if (a.cash > b.cash)
return -1;
if (a.cash < b.cash)
return 1;
return 0;
}
var obj = objArr.sort(compare);
response.send(obj);
但是返回的响应没有排序。
我该如何解决这个问题? 谢谢
最佳答案
一些注意事项:
您的代码按降序排序(不是无序的)。
您的代码正在使用
sort
的返回值。请注意,这会产生误导性的印象,即返回的数组与原始数组不同。都是同一个数组,所以一般最好不要使用返回值。您的排序可以更短:
// Ascending: return a.cash - bcash; // Or descending: return b.cash - a.cash;
上述#1 的证明:
var objArr = [
{
"cash": 100,
"uid": "LHy2qRGaf3nkWQgU4axO",
"name": "test2"
},
{
"cash": 1000000,
"uid": "01wFhCSlnd9vSDY4NIkx",
"name": "test"
},
{
"cash": 500,
"uid": "PBOhla0jPwI4PIeNmmPg",
"name": "test3"
}
];
function compare(a, b) {
console.log("a" + a.cash);
console.log("b" + b.cash);
if (a.cash > b.cash)
return -1;
if (a.cash < b.cash)
return 1;
return 0;
}
var obj = objArr.sort(compare);
console.log(obj);
.as-console-wrapper {
max-height: 100% !important;
}
#2 和 #3 的演示:
var objArr = [
{
"cash": 100,
"uid": "LHy2qRGaf3nkWQgU4axO",
"name": "test2"
},
{
"cash": 1000000,
"uid": "01wFhCSlnd9vSDY4NIkx",
"name": "test"
},
{
"cash": 500,
"uid": "PBOhla0jPwI4PIeNmmPg",
"name": "test3"
}
];
console.log("ascending", objArr.sort((a, b) => a.cash - b.cash));
console.log("descending", objArr.sort((a, b) => b.cash - a.cash))
.as-console-wrapper {
max-height: 100% !important;
}
关于javascript - Json 排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48035189/