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.
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.
-
“I tried with methods like
_.groupBy
,_.countBy
,_.sortBy
” — Can we please see those attempts? Please, edit your question and provide a minimal reproducible example. – Sebastian Simon Commented Apr 9, 2018 at 11:18 - 10 THIS IS NOT A DUPLICATE! This question asks for lodash and the dupe question is for underscore! Not the same! – Simon_Weaver Commented Jun 8, 2019 at 19:14
-
1
Great question. And your question being attacked seems to be another great example of peons projecting their delusions of self-importance via social media
gatekeeping
. – user3751385 Commented Dec 10, 2019 at 17:16
1 Answer
Reset to default 19Use _.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./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./ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>