Skip to content
Advertisement

How can I check if a value exists in Map in Javascript?

It looks a very easy question but I haven’t found it anywhere.

How can I know If an value exists in a Map?

For example:

A = [1,2,3,5,6,7]
var myMap = new Map();
for (let i = 0; i < A.length; i++) {
    myMap.set(i,A[i]);
}
for (let z = 1; z < Number.MAX_SAFE_INTEGER; z++) {
    console.log(z);
    if(!myMap.hasValue(z)){
        return z;
    }
}

I want to check if, given one value, this value is on the Hash. Like a “hasValue”.

Advertisement

Answer

You can use iterate over the map, look for the value and return true (exiting the loop) as soon as you find it. Or you return false if the element does not exist. Something like:

const findInMap = (map, val) => {
  for (let [k, v] of map) {
    if (v === val) { 
      return true; 
    }
  }  
  return false;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement