javascript Count the occurrences of a value in an array 1

javascript Count the occurrences of a value in an array

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);

// Examples
countOccurrences([2, 1, 3, 3, 2, 3], 2);                // 2
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a');  // 3

Here is what the above code is Doing:
1. The reduce() method is called on the array.
2. The callback function is invoked for each element in the array.
3. The callback function takes two arguments: the accumulator and the current element.
4. The accumulator is initialized to 0.
5. If the current element is equal to the value we’re looking for, the accumulator is incremented by 1.
6. The accumulator is returned.

Similar Posts