Get the element with the highest occurrence in an array

后端 未结 30 1740
野性不改
野性不改 2020-11-22 11:17

I\'m looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

[\'pear\', \'a         


        
30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 11:48

    This solution can return multiple elements of an array in case of a tie. For example, an array

    arr = [ 3, 4, 3, 6, 4, ];
    

    has two mode values: 3 and 6.

    Here is the solution.

    function find_mode(arr) {
        var max = 0;
        var maxarr = [];
        var counter = [];
        var maxarr = [];
    
        arr.forEach(function(){
           counter.push(0);
        });
    
        for(var i = 0;i max) {
                  max = arr[len];
                  }
          }
      return max;
     };
    
     function onlyUnique(value, index, self) {
           return self.indexOf(value) === index;
     }
    

提交回复
热议问题