Get the element with the highest occurrence in an array

后端 未结 30 1628
野性不改
野性不改 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:05

    You can try this:

     // using splice()   
     // get the element with the highest occurence in an array
        function mc(a) {
          var us = [], l;
          // find all the unique elements in the array
          a.forEach(function (v) {
            if (us.indexOf(v) === -1) {
              us.push(v);
            }
          });
          l = us.length;
          while (true) {
            for (var i = 0; i < l; i ++) {
              if (a.indexOf(us[i]) === -1) {
                continue;
              } else if (a.indexOf(us[i]) != -1 && a.length > 1) {
                // just delete it once at a time
                a.splice(a.indexOf(us[i]), 1);
              } else {
                // default to last one
                return a[0];
              }
            }
          }
        }
    
    // using string.match method
    function su(a) {
        var s = a.join(),
                uelms = [],
                r = {},
                l,
                i,
                m;
    
        a.forEach(function (v) {
            if (uelms.indexOf(v) === -1) {
                uelms.push(v);
            }
        });
    
        l = uelms.length;
    
        // use match to calculate occurance times
        for (i = 0; i < l; i ++) {
            r[uelms[i]] = s.match(new RegExp(uelms[i], 'g')).length;
        }
    
        m = uelms[0];
        for (var p in r) {
            if (r[p] > r[m]) {
                m = p;
            } else {
                continue;
            }
        }
    
        return m;
    }
    

提交回复
热议问题