Categories
JavaScript Answers

How to get key with the highest value from object with JavaScript?

Spread the love

Sometimes, we want to get key with the highest value from object with JavaScript.

In this article, we’ll look at how to get key with the highest value from object with JavaScript.

How to get key with the highest value from object with JavaScript?

To get key with the highest value from object with JavaScript, we can use the Objec.entries method.

For instance, we write

const data = { a: 1, b: 2, undefined: 3 };
const maxValue = Object.entries(data).sort((x, y) => y[1] - x[1])[0];

to call Object.entries with data to return an array with array of key-value pairs.

Then we call sort with a callback to sort each key-value pair array by its value.

And we get the first element from the sorted array which has the highest value in the data object.

Conclusion

To get key with the highest value from object with JavaScript, we can use the Objec.entries method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.