Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The most frequent item of an array using lodash [duplicate]

I'm looking for some help about an exercise where I have to return the item with the maximum occurrences in an array. I know there are other posts about this, but I can't find one which uses lodash only that I succeed to adapt.

For example :

var array = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3]

Should return : a (5times)

I tried with methods like ._groupBy, ._countBy, _.sortBy but I always find myself stuck at some point. Thanks.

like image 305
dmax Avatar asked Dec 13 '22 17:12

dmax


1 Answers

Use _.countBy() to get an object of element:count. Convert to an array of tuples using _.entries(). Find the max with _.maxBy(_.last), since the count value is the 2nd item in the tuple. Extract the element from the tuple using _.head().

var array = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];

var result = _.head(_(array)
  .countBy()
  .entries()
  .maxBy(_.last));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

And if you are importing specific methods from lodash, and don't want to use a chain use _.flow() instead:

var { countBy, entries, flow, head, last, maxBy, partialRight } = _;

var array = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];

var result = flow(
  countBy,
  entries,
  partialRight(maxBy, last),
  head
)(array);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
like image 111
Ori Drori Avatar answered Jan 12 '23 00:01

Ori Drori