Open In App

JavaScript Program to get Key by Value in a Map

Last Updated : 05 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to get a key by a value in a Map in JavaScript.Getting a key by a specific value in a JavaScript Map refers to finding the corresponding key associated with a given value stored within the Map collection.

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using map.entries() and for…of loop

In this approach,

  • The Map.prototype.entries() method returns the [key, value] pairs of all the elements of the map in the order of their insertions.
  • We use for…of loop to iterate through the entries of the map and check if the value ( the second element in the destructured array [key, value]) matches the searchKeyByValue.
  • If the key is found then it is returned; otherwise, we return undefined.

Syntax:

mapObj.entries()   //map.entries()
//for..of loop
for ( variable of iterableObjectName) {
...
};

Example: In this example we are using the above-explained apporach.

Javascript




function keyValue(map, searchKey) {
    for (const [key, value] of map.entries()) {
        if (value === searchKey)
            return key;
    }
    return undefined;
}
  
let students = new Map();
students.set('1', 'Diya');
students.set('2', 'Arav');
students.set('3', 'Priyanka');
students.set('4', 'Raj');
  
console.log(
    "Key associated with the value is: " + keyValue(students, 'Diya'));


Output

Key associated with the value is: 1

Approach 2: Using Map.forEach()

In this approach,

  • Create a function KeyByValue that takes a Map and a KeyValue as parameters.
  • Iterate through the Map using forEach, comparing each value with the provided KeyValue.
  • Assign the key to the result variable if a match is found; otherwise, keep the previous result.
  • Return the result variable, which contains the key associated with the specified KeyValue.

Syntax:

myMap.forEach(callback, value, key, thisArg)

Example: In this example we are using the above-explained approach.

Javascript




function KeyByValue(map, KeyValue) {
    let result;
    map.forEach((value, key) => {
        result = value === KeyValue ? key : result;
    });
    return result;
}
  
const students = new Map();
students.set('1', 'Diya');
students.set('2', 'Arav');
students.set('3', 'Priyanka');
students.set('4', 'Raj');
  
console.log(
    "Key associated with the value is: " + KeyByValue(students, 'Raj'));


Output

Key associated with the value is: 4

Approach 3: Using spread syntax, Array.filter(), and Array.map()

In this approach:

  • We convert the Map into an array of entries using spread syntax(…).
  • We use the Array.filter() iterative method which filters the entries based on the condition that the value of each entry must be equal to the searchKeyByValue.
  • Then we use Array.map() interative method which extracts the key from the filtered array.
  • If a matching entry is found, we return the key from that entry; otherwise, we return undefined.

Syntax:

let variablename1 = [...value];   //spread operator
array.filter(callback(element, index, arr), thisValue) //array.filter()
map((element, index, array) => { /* … */ }) //array.map()

Example: In this example we are using the above-explained apporach.

Javascript




function getKeyByValue(myMap, searchKeyByValue) {
    let myKey = [...myMap.entries()].filter(({ 1: v }) =>
        v === searchKeyByValue).map(([k]) => k);
    return myKey;
  
}
  
let students = new Map();
students.set('1', 'Diya');
students.set('2', 'Arav');
students.set('3', 'Priyanka');
students.set('4', 'Raj');
  
let key = getKeyByValue(students, 'Priyanka');
if (key != "")
    console.log("Key associated with the value is: " + key);
else
    console.log("Value does not exist in the map");


Output

Key associated with the value is: 3

Approach 4: Using Array.from() and Array.find() method

In this approach, we are using Array.from()

  • Create a Map called students and set key-value pairs.
  • Convert the map entries into an array using Array.from and find the entry with the value ‘Diya’ using the find method.
  • Determine the associated key (‘1’) if the entry is found, or set key to undefined if no match is found.

Syntax:

Array.from(object, mapFunction, thisValue)  //array.form()
array.find(function(currentValue, index, arr),thisValue); //array.find()

Example: In this example we are using the above-explained apporach.

Javascript




let students = new Map();
students.set('1', 'Diya');
students.set('2', 'Arav');
students.set('3', 'Priyanka');
students.set('4', 'Raj');
  
let arr1 = Array.from(students.entries());
const foundEntry = 
    arr1.find(([key, value]) => value === 'Diya');
  
let result = foundEntry ? foundEntry[0] : undefined;
console.log(
    "Key associated with the value is: " + result);


Output

Key associated with the value is: 1


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads