【问题标题】:Lodash - how to tally occurences in an arrayLodash - 如何计算数组中的出现次数
【发布时间】:2020-07-06 03:03:57
【问题描述】:

假设我们有一个数组:

const pets = ['Dog','Cat','Fish','Dog','Dog','Cat']

如何使用 lodash 以这种格式返回最常出现的对象?

{
  pet: 'Dog',
  number: 3
}

【问题讨论】:

    标签: javascript arrays lodash


    【解决方案1】:

    const pets = ['Dog', 'Cat', 'Fish', 'Dog', 'Dog', 'Cat'];
    const frequency =  _.maxBy(_.map(_.groupBy(pets), pet => ({ pet: pet[0], number: pet.length })), 'number');
    console.log(frequency);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    【讨论】:

      【解决方案2】:

      您可以使用_.countBy() 计算数组中宠物的频率。然后您可以获取频率条目并使用_.maxBy() 找到最大条目。获得最大条目后,您可以将其映射到对象:

      const popularPet = _.flow(
        _.countBy,
        o => _.maxBy(_.entries(o), _.last),
        ([pet, number]) => ({pet, number})
      );
      
      const res = popularPet(['Dog','Cat','Fish','Dog','Dog','Cat']);
      console.log(res);
      <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

      【讨论】:

        【解决方案3】:

        const pets = ['Dog','Cat','Fish','Dog','Dog','Cat'];
        const petsGrpByDups = _.groupBy(pets);
        console.log('******* GROUPBY DUPS *******');
        console.log(petsGrpByDups);
        
        let mostFreqOccs = _.reduce(petsGrpByDups, ({number,pet}, elem) => {
          return elem.length > number 
                 ? {number:elem.length, pet: elem[0]} 
                 : {number, pet };
        }, {number:0});
        
        console.log('******* MOST FREQ OCCURRED *******');
        console.log(mostFreqOccs);
        
        mostFreqOccs = _.maxBy(_.values(petsGrpByDups), elem => elem.length);
        
        console.log('******* MOST FREQ OCCURRED *******');
        console.log(mostFreqOccs);
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

        【讨论】:

          【解决方案4】:

          如果你对 lodash 不是很挑剔,下面是带有 forEachObject.entries 的纯 JS

          const pets = ["Dog", "Cat", "Fish", "Dog", "Dog", "Cat"];
          
          const words = {};
          pets.forEach((word) => (words[word] = (words[word] ?? 0) + 1));
          
          const [[pet, number]] = Object.entries(words).sort(([, a], [, b]) => b - a);
          
          const result = { pet, number };
          
          console.log(result);

          【讨论】:

            猜你喜欢
            • 2015-04-15
            • 2015-06-18
            • 1970-01-01
            • 2021-03-22
            • 2022-01-06
            • 1970-01-01
            • 2017-03-24
            相关资源
            最近更新 更多