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

如何根据指定键值查找对象数组中的重复项并统计出现次数

统计数组中相同键值对对象的出现次数

需求:遍历对象数组,统计具有相同type值的对象出现次数,生成一个新数组,每个元素包含name(对应原type的值)和count(出现次数)。

原代码存在的问题

原代码逻辑完全颠倒:

  • 初始acc为空数组,第一次循环找不到对应项会进入else分支,但此时item.count未定义,运算后会变成NaN
  • 后续循环的判断逻辑与操作完全错位,最终无法得到预期结果

正确解法

解法一:先用对象统计次数,再转数组

这种方式逻辑清晰,性能更优(避免每次循环调用find带来的O(n)开销):

const inventory = [
  { type: 'apples' },
  { type: 'bananas' },
  { type: 'apples' },
  { type: 'orange' },
  { type: 'orange' },
  { type: 'orange' },
];

// 先统计每个type的出现次数到对象中
const countMap = inventory.reduce((map, item) => {
  const type = item.type;
  map[type] = (map[type] || 0) + 1;
  return map;
}, {});

// 将统计对象转换为目标格式的数组
const duplicates = Object.entries(countMap).map(([name, count]) => ({
  name,
  count
}));

console.log(duplicates);

解法二:直接用reduce生成目标数组

如果要通过一次reduce完成需求,需正确判断当前type是否已在结果数组中:

const inventory = [
  { type: 'apples' },
  { type: 'bananas' },
  { type: 'apples' },
  { type: 'orange' },
  { type: 'orange' },
  { type: 'orange' },
];

const duplicates = inventory.reduce((acc, item) => {
  const existing = acc.find(i => i.name === item.type);
  if (existing) {
    existing.count += 1;
  } else {
    acc.push({ name: item.type, count: 1 });
  }
  return acc;
}, []);

console.log(duplicates);

预期输出

[
  { name: 'apples', count: 2 },
  { name: 'bananas', count: 1 },
  { name: 'orange', count: 3 }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 18:27:37