Underscore.js:查找数组中最常出现的值? [英] Underscore.js: Find the most frequently occurring value in an array?
问题描述
考虑以下简单数组:
var foods = ['hotdog', 'hamburger', 'soup', 'sandwich', 'hotdog', 'watermelon', 'hotdog'];
使用下划线
,是否有函数或我可以用来选择最常出现的值的函数组合(在这种情况下它是 hotdog
)?
With underscore
, is there a function or combination of functions I can use to select the most frequently occurring value (in this case it's hotdog
)?
推荐答案
var foods = ['hotdog', 'hamburger', 'soup', 'sandwich', 'hotdog', 'watermelon', 'hotdog'];
var result = _.chain(foods).countBy().pairs().max(_.last).head().value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
countBy :
将列表分组并返回每组中对象数
的计数。
countBy: Sorts a list into groups and returns a count for the number of objects in each group.
< a href =http://underscorejs.org/#pairs =nofollow noreferrer>对 :
将对象转换为列表[键,值]
对。
max :
返回列表中的最大值。如果提供了迭代器函数,它将用于每个值以生成值的排序标准。
max: Returns the maximum value in list. If an iterator function is provided, it will be used on each value to generate the criterion by which the value is ranked.
last :
返回数组的最后一个元素
last: Returns the last element of an array
head :
返回数组的第一个元素
head: Returns the first element of an array
连锁店 :
返回一个包装对象。在此对象上调用方法将继续返回包装对象,直到使用值。
chain: Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is used.
value :
提取包装对象的值。
value: Extracts the value of a wrapped object.
这篇关于Underscore.js:查找数组中最常出现的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!