Files
30-seconds-of-code/snippets/frequencies.md
30secondsofcode a88380728b Travis build: 1676
2020-01-03 13:37:17 +00:00

495 B

title, tags
title tags
frequencies array,intermediate

Returns 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] ? a[v] + 1 : 1;
    return a;
  }, {});
frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']); // { a: 4, b: 2, c: 1 }