如何实现统计数组中指定元素出现次数的函数
countOccurrences Function Hey there! Let's walk through a few straightforward, easy-to-understand ways to build this function that counts how many times a specific element shows up in an array.
Basic Approach: Using forEach Loop
This is a simple, readable method that iterates over each element and increments a counter whenever we hit a match:
// Define your target array (you can also pass this as a function parameter for more flexibility!) const targetArray = [5, 7, 12, 5, 3, 3, 5]; function countOccurrences(searchElement) { let count = 0; targetArray.forEach(element => { // Use strict equality (`===`) to avoid unexpected type coercion issues if (element === searchElement) { count++; } }); return count; } // Test it out! console.log(countOccurrences(3)); // Output: 2 console.log(countOccurrences(5)); // Output: 3
More Concise: Using reduce
The reduce method is perfect for accumulating values like a count—it’s shorter while still being easy to follow:
const targetArray = [5, 7, 12, 5, 3, 3, 5]; function countOccurrences(searchElement) { return targetArray.reduce((accumulator, currentElement) => { // Add 1 to the accumulator if we have a match, otherwise keep it unchanged return currentElement === searchElement ? accumulator + 1 : accumulator; }, 0); // Start with an initial count of 0 } // Test cases console.log(countOccurrences(3)); // Output: 2
Make It Reusable: Pass the Array as a Parameter
If you want the function to work with any array (not just a fixed one), modify it to accept the array as a first parameter—this makes it way more versatile:
function countOccurrences(arr, searchElement) { return arr.reduce((acc, curr) => { return curr === searchElement ? acc + 1 : acc; }, 0); } // Usage example const myArray = [5, 7, 12, 5, 3, 3, 5]; console.log(countOccurrences(myArray, 3)); // Output: 2
Quick Note on Equality
All the examples above use strict equality (===), which works great for primitive values (numbers, strings, booleans, etc.). If you need to count occurrences of reference types (like objects or arrays), you’ll need to adjust the comparison logic—for example, checking specific object properties or using JSON.stringify for shallow comparisons.
内容的提问来源于stack exchange,提问作者magniFITO

