Lodash - 如何计算数组中的出现次数



假设我们有一个数组:

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

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

{
pet: 'Dog',
number: 3
}

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>

您可以使用_.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>

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>

如果你对 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);

相关内容

  • 没有找到相关文章

最新更新