eolas/zk/Frequency_counters.md

33 lines
754 B
Markdown
Raw Normal View History

2022-07-02 15:30:14 +01:00
---
2022-08-21 11:00:04 +01:00
tags: []
2022-07-02 15:30:14 +01:00
---
# Frequency counters
Here is a concise method for counting the number instances of each type of array
element.
2022-07-02 15:30:14 +01:00
```js
function frequencyCounter(...inputArr) {
let counter = {};
inputArr.forEach((item) => {
2022-07-02 15:30:14 +01:00
// If item doesn't exist as a key in the counter, make 0 the val and add one
// If item already exists as key in the counter, increment it by one
counter[item] = (counter[item] || 0) + 1;
});
return counter;
2022-07-02 15:30:14 +01:00
}
```
An application of this would be checking for duplicates in an array:
```js
const testArr = [1, 4, 3, 3];
const arrayFreq = frequencyCounter(testArr);
let count = Object.values(arrayFreq);
2022-07-02 15:30:14 +01:00
if (count.some((ele) => ele > 1)) {
return "There are duplicates";
} else return "No duplicates";
```