按值对对象重新排序,但保留键和值

时间:2018-10-26 20:55:16

标签: javascript arrays sorting object

我有一个对象:

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

我想按值(从最高到最低)进行排序,这样它将是:

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

我尝试了一些操作,包括Object.keysArray.from,但是我无法显示键和值。在一分钟之内,我已经用正确的密钥订购了它,但是值丢失了:

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

keySorted是一个看起来像这样的数组:

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

顺序正确,但是我丢失了数值!

谢谢。

2 个答案:

答案 0 :(得分:1)

此输出表示是否适合您?:

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

如果是,则可能是代码:

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

答案 1 :(得分:1)

您需要将它们转换为可管理的源。我要做的是先将每个数组转换为键/值对象数组,然后将该数组从最高到最低排序。

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