Check if a Value exists in a Map using JavaScript


Borislav Hadzhiev

Tue Oct 19 20211 min read

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee