-1

So I working on a discord bot that has a rank system. I have got to the point where I have an object that looks like this:

let ranks = {
   "Joe": 1,
   "Mary": 6,
   "Johnson": 4
}

so I need to sort these in order of level so it looks like this:

let ranks = {
   "Mary": 6,
   "Johnson": 4,
   "Joe": 1
}

I have no idea how to do this. I have tried putting the values into lists and using names.sort() but that does not work. Any help would be appriciated.

  • 5
    Those are objects, not arrays and they don't guarantee order of properties. see: [Does JavaScript guarantee object property order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – pilchard Jan 18 '21 at 21:57
  • 2
    There's no array, nor JSON, in the question. That's why array functions like `sort()` do not work. That's an object, and object properties do not have an inherent order. – Heretic Monkey Jan 18 '21 at 21:57

2 Answers2

0

I don't see the reason to sort an object properties. U can transform the object to array for use sort thanks to Object.entries

For example

let sortedArr = Object.entries(ranks).sort((a,b) => (b[1] -a[1]));

and then you get your result by Object.fromEntries()

let sortedObj = Object.fromEntries(sortedArr)
3limin4t0r
  • 13,832
  • 1
  • 17
  • 33
moqiyuanshi
  • 524
  • 3
  • 17
0

use this code

let ranks = {
   "Joe": 1,
   "Mary": 6,
   "Johnson": 4,
   'Ahmed': 1

}
console.log( ranks)
//get the keys
var keys = Object.keys(ranks)
var testArray = [] ;

// get a new array to work on 
keys.forEach(key=>{
  testArray.push(key)  
})

// sort the keys
 
var sortedKeys = testArray.sort()

// get the right values of the sorted keys

var sortedVals = []
sortedKeys.forEach(Skey =>{
  sortedVals.push(ranks[Skey])
})

//clear the old ranks 

ranks = {}
var i = 0;

// get the new ranks object
sortedKeys.forEach(key=>{
  ranks[key] = sortedVals[i]
  i++
})

console.log( ranks)