Skip to main content

JavaScript function that returns an object with the unique values of an array as keys and their frequencies as the values.

/**
 * Calculate frequencies in Array.
 *
 * @param {array} arr
 * @returns {*}
 *
 * @example frequencies(["a", "b", "a", "c", "a", "a", "b"]); // { a: 4, b: 2, c: 1 }
 * @link https://www.30secondsofcode.org/js/s/frequencies/
 */
const frequencies = arr =>
    arr.reduce((a, v) => {
        a[v] = a[v] ? a[v] + 1 : 1;
        return a;
    }, {});

// ES5
var frequencies = function(arr) {
    return arr.reduce(function(a, v) {
        a[v] = a[v] ? a[v] + 1 : 1;
        return a;
    }, {});
};

//
// Example usage:
frequencies(["a", "b", "a", "c", "a", "a", "b"]); // { a: 4, b: 2, c: 1 }

//
// Also see:
// Get Most Frequent Element in an Array (https://jonlabelle.com/snippets/view/javascript/get-most-frequent-element-in-an-array)
//