Reputation: 99
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 ?
Upvotes: 0
Views: 1057
Reputation: 35222
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)
Upvotes: 1
Reputation: 205
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;
}
Upvotes: 0
Reputation: 14904
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.
Upvotes: 0