Underscore.js: Find the most frequently occurring value in an array?

前端 未结 3 1950
醉话见心
醉话见心 2020-12-14 19:45

Consider the following simple array:

var foods = [\'hotdog\', \'hamburger\', \'soup\', \'sandwich\', \'hotdog\', \'watermelon\', \'hotdog\'];
3条回答
  •  一向
    一向 (楼主)
    2020-12-14 20:19

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

提交回复
热议问题