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

如何在纯JavaScript中统计数字数组的出现次数

嘿,这个需求太常见了!在纯JavaScript里统计数字数组中元素的出现次数,我给你分享几个实用且高效的方法,不管是单个数组还是成百上千个集合都能轻松处理:

方法1:用普通对象实现基础统计

这是最直观的方式,利用对象的键存储数字,值存储对应出现次数:

// 示例数组
const numbers = [1, 2, 3, 2, 1, 3, 3, 3, 4];
const countObj = {};

// 遍历数组统计
for (const num of numbers) {
  // 如果数字已存在,次数+1;否则初始化为1
  countObj[num] = countObj[num] ? countObj[num] + 1 : 1;
}

console.log(countObj);
// 输出结果:{1: 2, 2: 2, 3: 4, 4: 1}
方法2:用Array.reduce()简化代码

reduce方法天生适合这种累加类的统计逻辑,一行核心代码就能搞定:

const numbers = [1, 2, 3, 2, 1, 3, 3, 3, 4];
const countResult = numbers.reduce((acc, curr) => {
  // 累加当前数字的出现次数,不存在则默认0
  acc[curr] = (acc[curr] || 0) + 1;
  return acc;
}, {}); // 初始值为空对象

console.log(countResult);
// 输出结果:{1: 2, 2: 2, 3: 4, 4: 1}
方法3:用Map处理更灵活的场景

如果你的数字集合里可能存在特殊类型(比如大整数、NaN等),Map会比普通对象更靠谱,它支持任意类型的键:

const numbers = [1, 2, 3, 2, 1, 3, 3, 3, 4];
const countMap = new Map();

for (const num of numbers) {
  // 用get获取当前次数,不存在则返回0,然后+1再存回去
  countMap.set(num, (countMap.get(num) || 0) + 1);
}

// 要是需要转换成普通对象格式,可以用Object.fromEntries
const countObj = Object.fromEntries(countMap);
console.log(countObj);
// 输出结果:{1: 2, 2: 2, 3: 4, 4: 1}
批量处理多个数组

如果你有成百上千个数字集合,把统计逻辑封装成函数就可以批量调用了:

function countOccurrences(arr) {
  return arr.reduce((acc, curr) => {
    acc[curr] = (acc[curr] || 0) + 1;
    return acc;
  }, {});
}

// 示例:处理多个数组
const arr1 = [1, 2, 3, 2];
const arr2 = [4, 5, 4, 4, 6];
console.log(countOccurrences(arr1)); // {1: 1, 2: 2, 3: 1}
console.log(countOccurrences(arr2)); // {4: 3, 5: 1, 6: 1}

这些方法的时间复杂度都是O(n),遍历一次数组就能完成统计,处理大规模数据也不会有性能问题~

内容的提问来源于stack exchange,提问作者Sergio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:52:00