Most frequent element in array

JavaScript, Array · Sep 15, 2020

Returns the most frequent element in an array.

const mostFrequent = arr =>
    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'

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Array permutations

    Generates all permutations of an array's elements (contains duplicates).

    JavaScript, Array · Dec 28, 2020

  • Remove matching elements from array

    Mutates an array by removing elements for which the given function returns false.

    JavaScript, Array · Oct 22, 2020

  • N random elements in array

    Gets n random elements at unique keys from an array up to the size of the array.

    JavaScript, Array · Oct 22, 2020