Skip to content

Home

Most frequent element in array

Returns the most frequent element in an array.

const mostFrequent = arr =>
  Object.entries(
    arr.reduce((a, v) => {
      a[v] = a[v] ? a[v] + 1 : 1;
      return a;
    }, {})
  ).reduce((a, v) => (v[1] >= a[1] ? v : a), [null, 0])[0];

mostFrequent(['a', 'b', 'a', 'c', 'a', 'a', 'b']); // 'a'

More like this

Start typing a keyphrase to see matching snippets.