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
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
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);
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)
Just adding adding another potential solution:
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)