You need to enable JavaScript to run this app. JavaScript使用reduce统计数组水果出现次数并重映射键名问题
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript使用reduce统计数组水果出现次数并重映射键名问题

问题排查与解决方法

你现有代码的问题主要有两处:

  • reduce的初始累加值用了数组[],但你要做的是按水果名做键的计数统计,用空对象{}作为初始值更符合键值对存储的需求
  • 直接判断item in allTypes逻辑错误,item是数组中的对象,隐式转为字符串后是固定的[object Object],无法区分不同水果,需要取item.fruit作为统计的唯一key

推荐实现(性能优先)

先统计为水果名-计数的对象,再映射为目标格式,时间复杂度为O(n):

const array = [{fruit: "Apple", cost: 2},{fruit: "Banana", cost: 3}, {fruit: "Apple", cost: 4}]

// 统计各水果出现次数
const countMap = array.reduce((acc, item) => {
  const fruitName = item.fruit
  acc[fruitName] = (acc[fruitName] || 0) + 1
  return acc
}, {})

// 转换为目标数组格式
const result = Object.entries(countMap).map(([fruit, count]) => ({
  fruit,
  count
}))

单reduce实现(小数据量可用)

如果不想做二次映射,也可以直接用一次reduce生成结果,时间复杂度为O(n²),适合数据量不大的场景:

const result = array.reduce((acc, item) => {
  const target = acc.find(entry => entry.fruit === item.fruit)
  target ? target.count++ : acc.push({ fruit: item.fruit, count: 1 })
  return acc
}, [])

两种方式最终得到的result都是你期望的[{fruit:"Apple", count:2}, {fruit:"Banana", count:1}]格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 05:06:04