demiglace
demiglace

Reputation: 773

Lodash - how to tally occurences in an array

Let's say we have an array:

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

How do I return an object of the most frequent occurence, in this format using lodash?

{
  pet: 'Dog',
  number: 3
}

Upvotes: 0

Views: 321

Answers (4)

Vinay
Vinay

Reputation: 2339

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>

Upvotes: 1

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11011

If you are not very particular about lodash, Following is with plain JS with forEach and Object.entries

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);

Upvotes: 0

Ziaullhaq Savanur
Ziaullhaq Savanur

Reputation: 2358

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>

Upvotes: 0

Nick Parsons
Nick Parsons

Reputation: 50974

You can count the frequencies of the pets in your array using _.countBy(). Then you can grab the entries of the frequencies and find the maximum entry using _.maxBy(). Once you've obtained the max entry, you can map it to an object:

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>

Upvotes: 1

Related Questions