Consider the following simple array:
var foods = [\'hotdog\', \'hamburger\', \'soup\', \'sandwich\', \'hotdog\', \'watermelon\', \'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:
var o = _(foods).reduce(function(o, s) {
o.freq[s] = (o.freq[s] || 0) + 1;
if(!o.freq[o.most] || o.freq[s] > o.freq[o.most])
o.most = s;
return o;
}, { freq: { }, most: '' });
That leaves 'hotdot' in o.most.
Demo: http://jsfiddle.net/ambiguous/G9W4m/
You can also do it with each (or even a simple for loop) if you don't mind predeclaring the cache variable:
var o = { freq: { }, most: '' };
_(foods).each(function(s) {
o.freq[s] = (o.freq[s] || 0) + 1;
if(!o.freq[o.most] || o.freq[s] > o.freq[o.most])
o.most = s;
});
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 say o.most to get 'hotdog'.