Reputation: 679
I am doing analysis on an array of strings named wordList: string[] = [];
This contains a long list of strings.
Problem: I have a map object whose key is a string
type and value is of type number
.
Here is my code.
private rankMostFrequent5Words(): void {
this.wordList.forEach((word:string) => {
if(!this.mapObject.has(word)) {
this.mapObject.set(word, 1)
}
else {
this.mapObject[word]++;
}
});
}
My desired output is: if a key already exists in the map then increment the number by 1 and if it does not exist set this key and count to 1.
Actual output:
How can I fix this ? Please guide.
Upvotes: 2
Views: 70
Reputation: 16837
You cannot access map values with bracket syntax. You must use the .get
method.
if(!this.mapObject.has(word)) {
this.mapObject.set(word, 1)
} else {
this.mapObject.set(word, this.mapObject.get(word) + 1)
}
Read more about Map.
Upvotes: 1