You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现统计数组中指定元素出现次数的函数

How to Implement the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 23:08:10