Count occurrences of value in array with reduce

Doesn't require creation of new array as with current solution.
This commit is contained in:
Thalis Kalfigkopoulos
2017-12-12 10:26:01 +01:00
parent c793bf4062
commit 39f720e9c3

View File

@ -5,3 +5,9 @@ Use `filter()` to create an array containing only the items with the specified v
```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);
```