Merge pull request #19 from tkalfigo/count-occurrences-of-value-in-array-with-reduce

Count occurrences of value in array with reduce
This commit is contained in:
Angelos Chalaris
2017-12-12 12:11:22 +02:00
committed by GitHub

View File

@ -5,3 +5,9 @@ Use `filter()` to create an array containing only the items with the specified v
```js ```js
var countOccurrences = (arr, value) => arr.filter(v => v === value).length; 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);
```