Consider the following simple array:
var foods = ['hotdog', 'hamburger', 'soup', 'sandwich', 'hotdog', 'watermelon', '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
)?
You can do this in one pass using
_.reduce
. The basic idea is to keep track of the word frequencies and the most common word at the same time:That leaves
'hotdot'
ino.most
.Demo: http://jsfiddle.net/ambiguous/G9W4m/
You can also do it with
each
(or even a simplefor
loop) if you don't mind predeclaring the cache variable:Demo: http://jsfiddle.net/ambiguous/WvXEV/
You could also break
o
into two pieces and use a slightly modified version of the above, then you wouldn't have to sayo.most
to get'hotdog'
.