Get the item that appears the most times in an array

Viewed 27028
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?

13 Answers

Another ES6 option. Works with strings or numbers.

function mode(arr) {
  const store = {}
  arr.forEach((num) => store[num] ? store[num] += 1 : store[num] = 1)
  return Object.keys(store).sort((a, b) => store[b] - store[a])[0]
}

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

Related