Skip to content
Advertisement

JavaScript: Get property with largest numerical value in object [closed]

I have an object like so:

const obj = {
    happy: 0.6,
    neutral: 0.1,
    said: 0.3
}

How do I get the property with the largest value (happy in this case)?

Advertisement

Answer

You can easily achieve this using Object.entries

const obj = {
  happy: 0.6,
  neutral: 0.1,
  said: 0.3,
};

const result = Object.entries(obj).sort((a, b) => b[1] - a[1])?.[0]?.[0];
console.log(result);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement