为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Qyouu 2021-11-12 18:24:01
我正在制作一个简单的 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 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

使用 Object.entries 进行简单的 reduce


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


查看完整回答
反对 回复 2021-11-12
?
12345678_0001

TA贡献1802条经验 获得超5个赞

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


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


查看完整回答
反对 回复 2021-11-12
?
SMILET

TA贡献1796条经验 获得超4个赞

按降序排序并获取第一项:


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


查看完整回答
反对 回复 2021-11-12
  • 3 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信