Check if a Value exists in a Map using JavaScript


Borislav Hadzhiev

Last updated: Oct 19, 2021


Photo from Unsplash

Check if a Value exists in a Map #

To check if a value exists in a map:

  1. Call the values() method on the Map to get an iterator, that contains the values in the Map object.
  2. Convert the iterator to an array and call the includes() method on the array, passing it the specific value as a parameter.
  3. The includes method returns true if the value is contained in the array and false otherwise.
const map = new Map(); map.set('lang', 'spanish'); // 👇️ ['spanish'] const values = []; console.log(values.includes('spanish')); // 👉️ true console.log(values.includes('english')); // 👉️ false

We used the Map.values method to get an iterator object, which contains the Map's values.

We used the spread operator (...) to unpack the values from the iterator into an array.

The last step is to use the Array.includes method to check if the value is contained in the array.

Here's the same approach, abstracted in a reusable function.

function valueInMap(map, value) { const values = []; if (values.includes(value)) { console.log('✅ value is contained in the Map'); return true; } console.log('⛔️ value is not contained in the Map'); return false; } const myMap = new Map(); myMap.set('lang', 'spanish'); // 👇️ true console.log(valueInMap(myMap, 'spanish')); // 👇️ false console.log(valueInMap(myMap, 'test'));
An array implements way more methods than a map does and it's quite easy to convert an iterator to an array.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.