Word Frequency Count, fix a bug with a standard property

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:

enter image description here

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

+3
source share
3 answers
function count(arr){
  return arr.reduce(function(m,e){
    m[e] = (+m[e]||0)+1; return m
  },{});
}

The idea is that

  • use reducefor elegance
  • m[e] +m[e], constructor ( toString)

+13
var arr = ['apple', 'orange', 'grape', 'apple'];
var initialValue = {};

var result = arr.reduce(function(accumulator, curr, idx, arr) {
    if (Object.hasOwnProperty.call(accumulator, curr)) {   // does current exist as key on initialValue object?
        accumulator[curr]++;
    } else {    // no key for current on initialValue object
        accumulator[curr] = 1;
    }
    return accumulator;
}, initialValue);

console.log(result);
0

You can also create an array by simply initializing [] as the initial accumulator.

var fruits = ['apple', 'orange', 'grape', 'apple'].reduce((countFruits,currentFruit)=>{
  if(typeof countFruits[currentFruit]!=="undefined"){
    countFruits[currentFruit] = countFruits[currentFruit]+1
    return countFruits
  }
  countFruits[currentFruit] = 1
  return countFruits
},[])
console.log(fruits) 
0
source

All Articles