-1

Here is our object:

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

How can we return c as it contains maximum value? there are simple solutions for arrays but I wonder how this one cloud be implemented

Sara Ree
  • 3,417
  • 12
  • 48
  • Possible duplicate of [Fast way to get the min/max values among properties of object](https://stackoverflow.com/questions/11142884/fast-way-to-get-the-min-max-values-among-properties-of-object) – Mehrdad Oct 12 '19 at 22:20

3 Answers3

1

Reduce the Object.entries of the object, where the accumulator contains the entry of the greatest value so far, then access the [0]th value of the entry:

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You can use Object.entries() to the key|value pairs, and then use Array.reduce() to find the pair with the maximum value. At the end extract the key from the pair.

const getMaxKey = o => Object.entries(o)
  .reduce((r, e) => e[1] > r[1] ? e : r)[0]

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

const result = getMaxKey(obj)

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

Just adding adding another potential solution:

  1. Find the max value
  2. The result is its index

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)
Melchia
  • 22,578
  • 22
  • 103
  • 117