Value frequencies

JavaScript, Array, Object · Sep 27, 2023

Creates an object with the unique values of an array as keys and their frequencies as the values.

  • Use Array.prototype.reduce() to map unique values to an object's keys, adding to existing keys every time the same value is encountered.
const frequencies = arr =>
  arr.reduce((a, v) => {
    a[v] = (a[v] ?? 0) + 1;
    return a;
  }, {});

frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']); // { a: 4, b: 2, c: 1 }
frequencies([...'ball']); // { b: 1, a: 1, l: 2 }

More like this

  • JavaScript Objects

    Handle JavaScript objects with ease, using the snippets and tips in this ES6 collection.

    Collection · 113 snippets

  • Index array based on function

    Creates an object from an array, using a function to map each value to a key.

    JavaScript, Array · Jun 20, 2021

  • Array to object based on key

    Creates an object from an array, using the specified key and excluding it from each value.

    JavaScript, Array · Jun 27, 2021

  • Filter matching and unspecified values

    Filters an array of objects based on a condition while also filtering out unspecified keys.

    JavaScript, Array · Oct 22, 2020