最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - The most frequent item of an array using lodash - Stack Overflow

programmeradmin5浏览0评论

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.

Share Improve this question edited Apr 9, 2018 at 12:07 p-a-o-l-o 10.1k2 gold badges24 silver badges36 bronze badges asked Apr 9, 2018 at 10:54 dmaxdmax 991 silver badge3 bronze badges 3
  • “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
Add a ment  | 

1 Answer 1

Reset to default 19

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./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>

发布评论

评论列表(0)

  1. 暂无评论