Reputation: 93
Assume
const words = ["hello", "this", "is", "hello", "this", "anything"]
let wordcount = {};
words.forEach((w) => {
if (wordcount[w]) {
wordcount.w = wordcount.w++;
} else {
wordcount.w = 1;
}
})
console.log(wordcount)
my expected output should be
{hello:2,this:2,is:1,anything:1}
Instead I am getting this-
{w:1}
why w get added as property instead of its value.
Upvotes: 1
Views: 62
Reputation: 17570
let y="test";
//While you use data.y then it means you create or update attribute with key y
var data={};
data.y=5;
console.log(data);
//While you use data[y] it means you create or update attribute with key as value of y
data[y]=2;
console.log(data);
so you use wordcount[w]
rather than wordcount.w
words=["hello","this","is","hello","this","anything"]
let wordcount={};
words.forEach((w)=>{
if(wordcount[w])
{
wordcount[w]++;
}
else{
wordcount[w]=1;
}
})
console.log(wordcount)
Upvotes: 1
Reputation: 486
use this:
let words = ["hello", "this", "is", "hello", "this", "anything"];
let wordCount = {};
words.forEach(w => {
if (wordCount[w] == undefined) wordCount[w] = 1;
else wordCount[w]++;
})
console.log(wordCount)
Upvotes: 0