This post will discuss how to retrieve the key with the largest value from a map in JavaScript.

There are several ways to get a key with maximum value in a map in JavaScript. Here are some possible functions:

1. Using Array.reduce() function

If we have a Map object as a map, we can use the Map.entries() function to get an iterator of the key-value pairs, and then use the Array.reduce() function to compare the values and return the pair with the maximum value. The following code illustrates this:

Download  Run Code

 
If we have an object literal as a map, we can use the Object.keys() function to get an array of keys, and then use the Array.reduce() function to compare the values and return the key with the maximum value. The following code illustrates this:

Download  Run Code

2. Using Array.filter() function

The Array.reduce() function will only return one pair, even if there are multiple pairs with the same maximum value. If we want to get an array of all the pairs with the maximum value, we can use the Array.filter() function instead. The following code illustrates its usage:

Download  Run Code

 
This function is simple and readable, but it requires an extra iteration. If we have an object literal as a map, we can do something like this:

Download  Run Code

3. Using a custom function

If we want a more generic and efficient way to get the min and max values in a map and the corresponding keys, we can use a custom function that takes a map as an argument and returns an object with four properties: minKey, minValue, maxKey, and maxValue. The function will iterate over the map’s entries only once and update these properties accordingly. The following code illustrates this:

Download  Run Code

 
This function will only return one key for each min and max value. If we want to get all the keys with the same min or max value, we can modify the function to use arrays instead of single values for the minKey and maxKey properties. However, this will also require more time and space to create and update these arrays. The following code illustrates this:

Download  Run Code

4. Using Lodash library

Finally, we can use a third-party library such as lodash for this task. Lodash has a function called _.maxBy(array, iteratee) that takes an array and an iteratee function as arguments and returns the element with the highest computed iteratee value. We can use this function to get the key with the maximum value from a map by passing it to the iteratee function. The following code illustrates its usage:

Download Code

 
This function will only return one key, even if there are multiple keys mapped with the maximum value. If we have an object literal as a map, we can do like:

Download Code

That’s all about retrieving the key with the largest value from a map in JavaScript.