0

I have an object:

 teamTotalChances = {
  AFC Wimbledon: 71.43,
  Accrington Stanley: 28.57,
  Barnsley: 64.28999999999999,
  Birmingham City: 114.28,
  Blackburn Rovers: 71.43
 }

That I want to order by the value (highest to lowest) so that it would then be:

teamTotalChances = {
 Birmingham City: 114.28,
 AFC Wimbledon: 71.43,
 Blackburn Rovers: 71.43,
 Barnsley: 64.28999999999999,
 Accrington Stanley: 28.57
}

I have tried a few things including Object.keys and Array.from but I can't get it to display key and value. At the minute I've got it ordered with the correct key but the value is lost:

keysSorted = Object.keys(teamTotalChances).sort(function(a,b){return 
teamTotalChances[b]-teamTotalChances[a]});

keySorted is then an Array which looks like this:

keySorted = [
 0: "Birmingham City",
 1: "AFC Wimbledon",
 2: "Blackburn Rovers",
 3: "Barnsley",
 4: "Accrington Stanley"
]

So the order is right, but I've lost the numeric value!

Thank you.

Bahman Parsa Manesh
  • 2,314
  • 3
  • 16
  • 32
user3725781
  • 595
  • 2
  • 7
  • 14

2 Answers2

1

Does this output representation suit you?:

[
  ["Birmingham City", 114.28],
  ["AFC Wimbledon", 71.43],
  ["Blackburn Rovers", 71.43],
  ["Barnsley", 64.28999999999999],
  ["Accrington Stanley", 28.57]
]

If yes, that could be the code:

 let teamTotalChances = {
  "AFC Wimbledon": 71.43,
  "Accrington Stanley": 28.57,
  Barnsley: 64.28999999999999,
  "Birmingham City": 114.28,
  "Blackburn Rovers": 71.43
 }

console.log(Object.entries(teamTotalChances).sort((a, b) => b[1] - a[1]))
Georgy
  • 2,410
  • 3
  • 21
  • 35
  • Yes, yes it does! Just a note for others this sorted it with lowest value first so I just swapped b[1] and a[1] around. I then looped through this array as so: teamEntries.forEach(function(team) { console.log(team[0]+ " "+team[1]); }); – user3725781 Oct 26 '18 at 21:27
1

You need to convert them to a manageable source. What I did is first convert each one to a key/value object array, then sorted that array from highest to lowest.

let teamTotalChances = {
  'AFC Wimbledon': 71.43,
  'Accrington Stanley': 28.57,
  'Barnsley': 64.28999999999999,
  'Birmingham City': 114.28,
  'Blackburn Rovers': 71.43
}

let result = Object.keys(teamTotalChances).map(itm => { return { key: itm, value: teamTotalChances[itm] } })

console.log(result.sort((a, b) => b.value - a.value))
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338