如何找到对象的最大值?

时间:2019-10-12 22:16:58

标签: javascript

这是我们的对象:

let obj = {a: 1, b: 3, c:10}

我们如何返回c,因为其中包含最大值? 阵列有简单的解决方案,但我想知道如何实现这一云

3 个答案:

答案 0 :(得分:1)

减少对象的Object.entries,该对象的累加器包含到目前为止的最大值,然后访问该条目的第[0]个值:

let obj = {a: 1, b: 3, c:10};

const maxProp = Object.entries(obj)
  .reduce((bestEntry, thisEntry) => thisEntry[1] > bestEntry[1] ? thisEntry : bestEntry)
  [0];
console.log(maxProp);

答案 1 :(得分:1)

您可以使用fontFamily "OpenSans" is not a system font and has not been loaded through Font.loadAsync. - If you intended to use a system font, make sure you typed the name correctly and that it is supported by your device operating system. - If this is a custom font, be sure to load it with Font.loadAsync. - node_modules\react-native\Libraries\YellowBox\YellowBox.js:59:8 in error - node_modules\expo\build\environment\muteWarnings.fx.js:27:24 in error - ... 24 more stack frames from framework internals 来设置键|值对,然后使用Object.entries()查找具有最大值的对。最后,从配对中提取密钥。

Array.reduce()

答案 2 :(得分:1)

只需添加添加另一个可能的解决方案:

  1. 找到最大值
  2. 结果是它的索引

let obj = {a: 1, b: 3, c:10}
max = Math.max(...Object.values(obj))
maxIndex = Object.keys(obj).find(key => obj[key] === max)
console.log(maxIndex)

相关问题