diff --git a/snippets/frequencies.md b/snippets/frequencies.md new file mode 100644 index 000000000..03b0918ec --- /dev/null +++ b/snippets/frequencies.md @@ -0,0 +1,22 @@ +--- +title: frequencies +tags: 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. + +```js +const frequencies = arr => + arr.reduce( + (a, v) => { + a[v] = a[v] ? a[v] + 1 : 1; + return a; + }, {} + ); +``` + +```js +frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']); // { a: 4, b: 2, c: 1 } +``` diff --git a/test/frequencies.test.js b/test/frequencies.test.js new file mode 100644 index 000000000..eef0c2dd8 --- /dev/null +++ b/test/frequencies.test.js @@ -0,0 +1,8 @@ +const {frequencies} = require('./_30s.js'); + +test('frequencies is a Function', () => { + expect(frequencies).toBeInstanceOf(Function); +}); +test('returns the appropriate object', () => { + expect(frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b'])).toEqual({ a: 4, b: 2, c: 1 }); +});