Get the item that appears the most times in an array

后端 未结 12 1525
太阳男子
太阳男子 2020-11-27 19:18
var store = [\'1\',\'2\',\'2\',\'3\',\'4\'];

I want to find out that 2 appear the most in the array. How do I go about doing that?

12条回答
  •  鱼传尺愫
    2020-11-27 19:42

    All the solutions above are iterative.

    Here's a ES6 functional mutation-less version:

    Array.prototype.mostRepresented = function() {
      const indexedElements = this.reduce((result, element) => {
        return result.map(el => {
          return {
            value: el.value,
            count: el.count + (el.value === element ? 1 : 0),
          };
        }).concat(result.some(el => el.value === element) ? [] : {value: element, count: 1});
      }, []);
      return (indexedElements.slice(1).reduce(
        (result, indexedElement) => (indexedElement.count > result.count ? indexedElement : result),
        indexedElements[0]) || {}).value;
    };
    

    It could be optimized in specific situations where performance is the bottleneck, but it has a great advantage of working with any kind of array elements.

    The last line could be replaced with:

      return (indexedElements.maxBy(el => el.count) || {}).value;
    

    With:

    Array.prototype.maxBy = function(fn) {
      return this.slice(1).reduce((result, element) => (fn(element) > fn(result) ? element : result), this[0]);
    };
    

    for clarity

提交回复
热议问题