This post will discuss how to extract all keys with a specific value from a Map in JavaScript.

To extract all keys with a specific value from a Map in JavaScript, we need to iterate through the map entries and compare the values with the given value using strict equality operator (===). We can use different functions to do this, such as:

1. Using Map.forEach() function

The Map.forEach() function executes a callback function for each entry in the map. The callback function can access the key and the value of the current pair and check if the value matches the given value. If it does, it can add the key to an array of keys. For example, we can use the following code snippet to retrieve all keys having the value 4 in a map:

Download  Run Code

 
Alternatively, we can use for…of loop to iterates over the maps. We can use this loop to access the key and value of each entry in the map and compare the value with the given value. If they match, we can add the key to an array. The following code illustrates this:

Download  Run Code

2. Using Array.filter() function

The idea is to convert the map into an array of key-value pairs using the Array.from() function or the spread operator (…). Then we can use Array.filter() function to filter out the key-value pairs that have the given value in the map. The filter function creates a new array with all elements that pass a test implemented by a callback function. Finally, we can use the Array.map() function to extract only the keys from the filtered array. Here’s an example:

Download  Run Code

3. Using a custom function

Finally, we can use a custom function that takes a map and a value as parameters and returns an array of keys. This is a more reusable and modular way, but it requires us to write and maintain our own function. This works well if we need more control over how the values are compared or if we want to reuse the function for different maps and values. However, it does not work if we want to use a more concise or functional style of coding. Here’s an example of how we can achieve this:

Download  Run Code

That’s all about extracting all keys with a specific value from a Map in JavaScript. All above functions works well for maps that contain primitive values, such as numbers, strings, booleans, etc.