Add frequencies
This commit is contained in:
22
snippets/frequencies.md
Normal file
22
snippets/frequencies.md
Normal file
@ -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 }
|
||||
```
|
||||
8
test/frequencies.test.js
Normal file
8
test/frequencies.test.js
Normal file
@ -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 });
|
||||
});
|
||||
Reference in New Issue
Block a user