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".
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.
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.
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.
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.
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.
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;
}
For me it works:
Object.values(myMap).includes(myValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With