简体   繁体   中英

How to check for a non existing value in a map typescript?

I have the below map in typescript:

myMap = {"a" => 1, "b" => 2, "c" => 4, "d" => 5}

The values can be 1 , 2 , 3, 4, or 5 only.

I need to check for the values in the myMap from 1 to 5 and if any of the value is missing, i want to log it and exit the loop. Eg: In the above map, value 3 is missing. So, i would want to log that value.

Can anyone let me know, how this could be achieved in typescript ?

You could create a Set of the values in Map . Then filter the numbers array and check if the set has each number

 const numbers = [1, 2, 3, 4, 5], map = new Map([ ["a", 1], ["b", 2], ["c", 4] ]), set = new Set(map.values()), missing = numbers.filter(n => !set.has(n)) console.log(missing)

That something more javascript specific then typescript.

var myMap = new Map();
myMap.set("a", 1);
myMap.set("b", 2);

let hasThree = [...myMap.values()].includes(3);

console.log(hasThree);

You can use .values() and spread it into an array and use then .includes

在此处输入图片说明

Here is an image that shows all methods of the Map prototype.

Taking into consideration that values are 1 to 5 , you could change array as well and use some other values with specific range and use it with map with this -

 var map = new Map(); map.set('a', 1) map.set('b', 2) map.set('c',4) map.set('d', 5) var arr = []; for(var singleVal of map.values()) arr.push(singleVal) var originalArr = [ 1, 2, 3, 4, 5]; // taking into consideration that you have some original array like this, where '3' is present for(var i=0; i<originalArr.length; i++) if(!arr.includes(originalArr[i])) { console.log(originalArr[i]); break; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM