Get the element with the highest occurrence in an array

后端 未结 30 1273
野性不改
野性不改 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 12:08

    This function is generic function for every type of info. It counts the occurrence of the elements and then returns array with maximum occurring elements.

    function mode () {
      var arr = [].slice.call(arguments);
      if ((args.length == 1) && (typeof args[0] === "object")) {
        args = args[0].mode();
      }
    
      var obj = {};
      for(var i = 0; i < arr.length; i++) {
        if(obj[arr[i]] === undefined) obj[arr[i]] = 1;
        else obj[arr[i]]++;
      }
    
      var max = 0;
      for (w in obj) {
        if (obj[w] > max) max = obj[w];
      }
    
      ret_val = [];
      for (w in obj) {
        if (obj[w] == max) ret_val.push(w);
      }
    
      return ret_val;
    }
    

提交回复
热议问题