I am trying to create a javascript function that will count the number of occurrences of each word in an input array.
Example:
Enter
a=["a","booster","booster","constructor","adam","adam","adam","adam"]
Output:
"a":1
"booster":2
"constructor":1
"adam":4
The output should be different.
I am new to javascript and I tried using dict. But objects have a constructor property, so cnt ["constructor"] does not seem to work.
Here is my code and result:
var cnt={};
console.log("constructor");
for(var i=0;i<a.length;++i)
{
if(! (a[i] in cnt))
cnt[a[i]]=0;
else
cnt[a[i]]+=1;
}
for(var item in cnt)
console.log(item+":"+cnt[item]);
Result:

You can see that 1 is added to the cnt constructor as a string.
source
share