Find the most frequent item of an array (not just strings)

后端 未结 7 2170
抹茶落季
抹茶落季 2020-12-10 19:42

Can someone walk me through this exercise? Write a JavaScript program to find the most frequent item of an array.

相关标签:
7条回答
  • 2020-12-10 20:39

    This is an answer to point (3) using underscore:

    function length(a) { return a.length; }
    
    _.max(_.groupBy(arr1), length)[0]
    

    How this works:

    > arr1 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
    
    > groups = _.groupBy(arr1)
    < { 2: [2,2], 3: [3,3,3,3], 4: [4], 9: [9], a: ['a', 'a', ...] }
    
    > max_group = _.max(groups, length)
    < ['a', 'a', ...]
    
    > max_group [0]
    < 'a'
    
    0 讨论(0)
提交回复
热议问题