Word Frequency Count, fix a bug with standard property

前端 未结 3 834
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 16:10

I\'m trying to build a javascript function which would count the number of occurrences of each word in an input array.

Example :

Input

a=[\"a         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 16:52

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

    The idea behind are

    • the use of reduce for elegance
    • the conversion of m[e] to a number using +m[e] to avoid the constructor (or toString) problem

    Demonstration

提交回复
热议问题