Count occurrences of value in array with reduce
Doesn't require creation of new array as with current solution.
This commit is contained in:
@ -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);
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user