Word Frequency Count, fix a bug with standard property

前端 未结 3 830
佛祖请我去吃肉
佛祖请我去吃肉 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

    0 讨论(0)
  • 2020-12-03 17:02

    You can also create an array just by 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 讨论(0)
  • 2020-12-03 17:08
    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 讨论(0)
提交回复
热议问题