返回对象数组中具有最大值的键的最简单方法是什么?

时间:2019-10-08 14:57:56

标签: javascript arrays sorting

我正在制作一个简单的RPG,并尝试计算角色升级时应增加哪个属性。它们对每个属性都有一个潜在的限制,我想增加距离其潜力最远的属性。

我可以遍历每个属性,并从其潜在值中减去其当前值以获得差值。然后,我可以将差异推到数组中。结果如下:

[
{Strength: 5},
{Dexterity: 6},
{Constitution: 3},
{Wisdom: 4},
{Charisma: 8}
]

魅力是具有最大差异的键,那么如何评估此值并返回键的名称(而不是值本身)?

编辑:这是用于获取数组的逻辑:

let difference = [];
let key;
for (key in currentAttributes) {
  difference.push({[key]: potentialAttributes[key] - currentAttributes[key]});
};

3 个答案:

答案 0 :(得分:5)

使用Object.entries进行简单归约

const items = [
  { Strength: 5 },
  { Dexterity: 6 },
  { Constitution: 3 },
  { Wisdom: 4 },
  { Charisma: 8 }
]

const biggest = items.reduce((biggest, current, ind) => {
  const parts = Object.entries(current)[0]  //RETURNS [KEY, VALUE]
  return (!ind || parts[1] > biggest[1]) ? parts : biggest  // IF FIRST OR BIGGER
}, null) 
console.log(biggest[0])  // 0 = KEY, 1 = BIGGEST VALUE

您的数据模型对于带有对象的数组有点奇怪,一个更好的模型就是一个对象。

const items = {
  Strength: 5,
  Dexterity: 6,
  Constitution: 3,
  Wisdom: 4,
  Charisma: 8
}

const biggest = Object.entries(items)
  .reduce((biggest, current, ind) => {
    const parts = current
    return (!ind || parts[1] > biggest[1]) ? parts : biggest  
}, null) 

console.log(biggest[0])

答案 1 :(得分:3)

您可以创建一个对象,获取条目并通过获取具有最大值的条目来减少条目。最后,从条目中获取密钥。

var data = [{ Strength: 5 }, { Dexterity: 6 }, { Constitution: 3 }, { Wisdom: 4 }, { Charisma: 8 }],
    greatest = Object
        .entries(Object.assign({}, ...data))
        .reduce((a, b) => a[1] > b[1] ? a : b)
        [0];

console.log(greatest);

答案 2 :(得分:2)

以降序排列并抓取第一项:

let attributes = [
  {Strength: 5},
  {Dexterity: 6},
  {Constitution: 3},
  {Wisdom: 4},
  {Charisma: 8}
];

//for convenience
const getValue = obj => Object.values(obj)[0];

//sort descending
attributes.sort((a, b) => getValue(b) - getValue(a));

let highest = attributes[0];
console.log(Object.keys(highest)[0]);

或者,通过数组查找最高分数:

let attributes = [
  {Strength: 5},
  {Dexterity: 6},
  {Constitution: 3},
  {Wisdom: 4},
  {Charisma: 8}
];

//for convenience
const getValue = obj => Object.values(obj)[0];

//find the highest score
let highest = attributes.reduce((currentHighest, nextItem) => getValue(currentHighest) > getValue(nextItem) ?  currentHighest : nextItem);

console.log(Object.keys(highest)[0]);