Files
30-seconds-of-code/snippets/count-occurrences-of-a-value-in-array.md
Thalis Kalfigkopoulos 39f720e9c3 Count occurrences of value in array with reduce
Doesn't require creation of new array as with current solution.
2017-12-12 10:26:01 +01:00

14 lines
467 B
Markdown

### Count occurrences of a value in array
Use `filter()` to create an array containing only the items with the specified value, count them using `length`.
```js
var countOccurrences = (arr, value) => arr.filter(v => v === value).length;
```
Use reduce() to increment a counter each time you encounter the specific value; does not create new array like filter().
```js
var countOccurrences = (arr, value) => arr.reduce((a, v) => v===value ? a + 1 : a + 0, 0);
```