Add frequencies

This commit is contained in:
Angelos Chalaris
2020-01-03 15:32:35 +02:00
parent 4b19a020db
commit a3fdf9c6c4
2 changed files with 30 additions and 0 deletions

22
snippets/frequencies.md Normal file
View 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 }
```