Check if a Value exists in a Map using JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 19, 2021

banner

Check out my new book

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.
index.js
const map = new Map(); map.set('lang', 'spanish'); // 👇️ ['spanish'] const values = [...map.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.

index.js
function valueInMap(map, value) { const values = [...map.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 #

Use the search field on my Home Page to filter through my more than 3,000 articles.