Get the element with the highest occurrence in an array

后端 未结 30 1191
野性不改
野性不改 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;
    }
    
    0 讨论(0)
  • 2020-11-22 12:09
    function mode(){
      var input = $("input").val().split(",");
      var mode = [];
      var m = [];
      var p = [];
        for(var x = 0;x< input.length;x++){
          if(m.indexOf(input[x])==-1){
            m[m.length]=input[x];
        }}
      for(var x = 0; x< m.length;x++){
        p[x]=0;
        for(var y = 0; y<input.length;y++){
          if(input[y]==m[x]){
          p[x]++; 
     }}}
     for(var x = 0;x< p.length;x++){
       if(p[x] ==(Math.max.apply(null, p))){
         mode.push(m[x]);
     }} 
    $("#output").text(mode);}
    
    0 讨论(0)
  • 2020-11-22 12:10
    a=['pear', 'apple', 'orange', 'apple'];
    b={};
    max='', maxi=0;
    for(let k of a) {
      if(b[k]) b[k]++; else b[k]=1;
      if(maxi < b[k]) { max=k; maxi=b[k] }
    }
    
    0 讨论(0)
  • 2020-11-22 12:12

    There have been some developments in javascript since 2009 - I thought I'd add another option. I'm less concerned with efficiency until it's actually a problem so my definition of "elegant" code (as stipulated by the OP) favours readability - which is of course subjective...

    function mode(arr){
        return arr.sort((a,b) =>
              arr.filter(v => v===a).length
            - arr.filter(v => v===b).length
        ).pop();
    }
    
    mode(['pear', 'apple', 'orange', 'apple']); // apple
    

    In this particular example, should two or more elements of the set have equal occurrences then the one that appears latest in the array will be returned. It's also worth pointing out that it will modify your original array - which can be prevented if you wish with an Array.slice call beforehand.


    Edit: updated the example with some ES6 fat arrows because 2015 happened and I think they look pretty... If you are concerned with backwards compatibility you can find this in the revision history.

    0 讨论(0)
  • 2020-11-22 12:13

    Here is another ES6 way of doing it with O(n) complexity

    const result = Object.entries(
        ['pear', 'apple', 'orange', 'apple'].reduce((previous, current) => {
            if (previous[current] === undefined) previous[current] = 1;
            else previous[current]++;
            return previous;
        }, {})).reduce((previous, current) => (current[1] >= previous[1] ? current : previous))[0];
    console.log("Max value : " + result);
    
    0 讨论(0)
  • 2020-11-22 12:14

    This is just the mode. Here's a quick, non-optimized solution. It should be O(n).

    function mode(array)
    {
        if(array.length == 0)
            return null;
        var modeMap = {};
        var maxEl = array[0], maxCount = 1;
        for(var i = 0; i < array.length; i++)
        {
            var el = array[i];
            if(modeMap[el] == null)
                modeMap[el] = 1;
            else
                modeMap[el]++;  
            if(modeMap[el] > maxCount)
            {
                maxEl = el;
                maxCount = modeMap[el];
            }
        }
        return maxEl;
    }
    
    0 讨论(0)
提交回复
热议问题