Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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".

like image 319
Fernando Maymone Avatar asked Apr 28 '18 13:04

Fernando Maymone


People also ask

How do you check if a key exists in a Map typescript?

To check if a Map has an object key, call the has() method, passing it a reference to the object, e.g. map.has(obj) . The has() method will return true if the object key is contained in the Map and false otherwise.

How do you check if a key has a value in JavaScript?

Use the in operator to check if a key exists in an object, e.g. "key" in myObject . The in operator will return true if the key is present in the object, otherwise false is returned.

How do you check if an object is a Map?

Use the instanceof operator to check if an object is a Map - myObj instanceof Map . The instanceof operator returns true if the prototype property of a constructor appears in the prototype chain of the object.

How do I iterate a Map in JavaScript?

Iterate through a Map using JavaScript # Use the forEach() method to iterate over a Map object. The forEach method takes a function that gets invoked for each key/value pair in the Map , in insertion order. The function gets passed the value, key and the Map object on each iteration.


3 Answers

You cannot, other than by searching through it:

Array.from(myMap.values()).includes(val)

Use an appropriate data structure instead, like a set of all the values:

A = [1,2,3,5,6,7]
var myValues = new Set(A);

for (let z = 1; z < Number.MAX_SAFE_INTEGER; z++) {
    console.log(z);
    if(!myValues.has(z)) {
        return z;
    }
}

Of course, given the fact that your A is sorted already, you could iterate it directly to find the lowest missing value.

like image 166
Bergi Avatar answered Oct 09 '22 06:10

Bergi


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;
}
like image 31
Dario Avatar answered Oct 09 '22 05:10

Dario


For me it works:

Object.values(myMap).includes(myValue);
like image 21
Wiktor Kujawa Avatar answered Oct 09 '22 05:10

Wiktor Kujawa