Skip to main content

JavaScript function to calculate the most frequent element in an array.

/**
 * Returns the most frequent element in an array.
 *
 * @param {array} arr
 * @returns {string}
 *
 * @example mostFrequent(["a", "b", "a", "c", "a", "a", "b"]); // "a"
 * @link https://www.30secondsofcode.org/js/s/most-frequent/
 */
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];

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

//
// Example usage:
mostFrequent(["a", "b", "a", "c", "a", "a", "b"]); // 'a'

//
// Also see:
// Calculate Frequencies in Array (https://jonlabelle.com/snippets/view/javascript/calculate-frequencies-in-array)
//