Most frequent element in array

JavaScript, Array · Sep 15, 2020

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

  • 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

  • Partition array in two

    Groups the elements into two arrays, depending on the provided function's truthiness for each element.

    JavaScript, Array · Nov 3, 2020

  • Toggle element in array

    Removes an element from an array if it's included in the array, or pushes it to the array if it isn't.

    JavaScript, Array · Apr 15, 2022