简体   繁体   中英

How to Sort object arrays by its key value

I have Object with arrays like below , I am trying to sort it ascending and descending by its value (rank)

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]

So output array is like below if descending .. and reverse for ascending

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]

I tried following code

scorearr.sort((obj1, obj2) => obj1.bnrank - obj2.bnrank);

And also below code

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);

Still scorearr is unchanged and its in old order only.

Edit : Below is sample data

{
  "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
  }
}

This is how I am creating this object ,please tell me if any alternative if this thing can be done easily.

var scorearr = {};
//loop here
var id = $(this).attr('id');
scorearr[id] = {};
scorearr[id] = {rank:nfscore,bnrank:bnscore,bs:sellscore,ss:buyscore};
//end loop

If you have an object with nested objects, you could take the entries (key/value pairs), sort this array and rebuild a new object with the sorted order.

 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; } 

Another approach with an array.

 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; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM