我的Object的数组如下所示,我正在尝试按值的升序和降序对它进行排序
AXISBANK: [rank: 110, bnrank: 110, bs: 75, ss: 3]
BANKBARODA: [rank: 32, bnrank: 5, bs: 83, ss: 26]
HDFCBANK: [rank: 453, bnrank: 453, bs: 52, ss: 33]
因此,如果输出数组降序为..,则输出数组如下所示。
HDFCBANK: [rank: 453, bnrank: 453, bs: 52, ss: 33]
AXISBANK: [rank: 110, bnrank: 110, bs: 75, ss: 3]
BANKBARODA: [rank: 32, bnrank: 5, bs: 83, ss: 26]
我尝试了以下代码
scorearr.sort((obj1, obj2) => obj1.bnrank - obj2.bnrank);
还有下面的代码
function compares(a,b) {
console.log(a.bnrank);
if (a.bnrank < b.bnrank)
return -1;
if (a.bnrank > b.bnrank)
return 1;
return 0;
}
scorearr.sort(compares);
静态记分器保持不变,并且仅按旧顺序显示。
编辑:以下是示例数据
{
"HDFCBANK": {
"rank": 453,
"bnrank": 453,
"bs": 52,
"ss": 33
},
"ICICIBANK": {
"rank": 228,
"bnrank": 228,
"bs": 88,
"ss": 3
},
"KOTAKBANK": {
"rank": 164,
"bnrank": 164,
"bs": 23,
"ss": 82
}
}
这就是我创建此对象的方式,请告诉我是否有其他选择可以轻松实现。
var scorearr = {};
//loop here
var id = $(this).attr('id');
scorearr[id] = {};
scorearr[id] = {rank:nfscore,bnrank:bnscore,bs:sellscore,ss:buyscore};
//end loop
答案 0 :(得分:3)
如果您有一个带有嵌套对象的对象,则可以获取条目(键/值对),对该数组进行排序,然后按排序顺序重建一个新对象。
var data = { AXISBANK: { rank: 110, bnrank: 110, bs: 75, ss: 3 }, BANKBARODA: { rank: 32, bnrank: 5, bs: 83, ss: 26 }, HDFCBANK: { rank: 453, bnrank: 453, bs: 52, ss: 33 } },
sorted = Object.assign(...Object
.entries(data)
.sort(({ 1: { bnrank: a } }, { 1: { bnrank: b } }) => b - a)
.map(([k, v]) => ({ [k]: v }))
);
console.log(sorted);
.as-console-wrapper { max-height: 100% !important; top: 0; }
另一种使用数组的方法。
var data = [{ id: 'AXISBANK', rank: 110, bnrank: 110, bs: 75, ss: 3 }, { id: 'BANKBARODA', rank: 32, bnrank: 5, bs: 83, ss: 26 }, { id: 'HDFCBANK', rank: 453, bnrank: 453, bs: 52, ss: 33 }];
data.sort(({ bnrank: a }, { bnrank: b }) => b - a);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }