Count number of occurrences in array with JavaScript | Javascript

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

AI Explanation

This code defines a function called `countOccurrences` that takes an array `arr` and a value `val` as input. It uses the `reduce` method to iterate over the elements of the array and accumulate a count of occurrences of the specified value `val`. Here's a breakdown of the code: - `arr.reduce((a, v) => (v === val ? a + 1 : a), 0);`: - `arr.reduce` is used to iterate over each element in the array and accumulate a value. - It takes a function that accepts two parameters `a` (accumulator) and `v` (current value). - For each element `v` in the array, it checks if `v` is equal to the specified value `val`. - If `v` is equal to `val`, it returns `a + 1` (increments the count). - If not, it returns the accumulator `a` unchanged. - The initial value of the accumulator is set to `0`. - `const countOccurrences = (arr, val) => ...`: - Defines a function called `countOccurrences` that takes an array `arr` and a value `val` as arguments. - The function uses an arrow function expression to define its behavior. Overall, this function calculates the number of times a specific value occurs in an array. It returns the count of occurrences of the specified value `val`.