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

数组过滤与元素求和:糖果对象数组分类成本统计求助

没问题!我来帮你搞定这个分类统计糖果成本的需求~ 核心思路就是按口感类型分组累加成本,再找出最大值,下面给你具体的实现方案:

分步实现方案

1. 核心思路拆解

  • 先创建一个「统计容器」,用来存储不同口感(consistency)对应的总成本
  • 遍历你的糖果数组,把每个糖果的cost加到对应口感的统计项里
  • 最后从统计结果里找出成本最高的那一项

2. 代码示例(JavaScript版本)

假设你的糖果数组结构类似这样(可以直接替换成你实际的数组):

// 你的糖果对象数组
const candies = [
  { name: '水果硬糖', consistency: 'hard', cost: 1.8 },
  { name: '棉花糖', consistency: 'soft', cost: 2.5 },
  { name: '牛奶硬糖', consistency: 'hard', cost: 2.2 },
  { name: '酥心糖', consistency: 'crunchy', cost: 3.0 },
  { name: 'QQ糖', consistency: 'soft', cost: 1.9 }
];

然后执行统计逻辑:

// 初始化统计对象,键是口感类型,值是累计成本
const totalCosts = {};

// 遍历数组累加成本
candies.forEach(candy => {
  const { consistency, cost } = candy;
  // 如果该口感类型还没被记录,先初始化为0
  if (!totalCosts[consistency]) {
    totalCosts[consistency] = 0;
  }
  // 累加当前糖果的成本
  totalCosts[consistency] += cost;
});

// 找出总成本最高的类型和数值
let highestCost = 0;
let highestConsistency = '';

// 遍历统计结果的键值对
for (const [type, cost] of Object.entries(totalCosts)) {
  if (cost > highestCost) {
    highestCost = cost;
    highestConsistency = type;
  }
}

// 输出结果
console.log('各类型糖果总成本:', totalCosts);
console.log(`总成本最高的是${highestConsistency},总计:${highestCost.toFixed(2)}`);

3. 代码关键点说明

  • 用forEach遍历数组,解构赋值快速获取consistency和cost,代码更简洁
  • 统计对象初始化时做了空值判断,避免第一次累加时出现NaN
  • 用Object.entries把统计对象转成键值对数组,方便遍历比较最大值
  • 最后用toFixed(2)格式化成本,避免小数位数过多的问题

4. Python版本参考(如果用Python实现)

# 糖果数组
candies = [
    {"name": "水果硬糖", "consistency": "hard", "cost": 1.8},
    {"name": "棉花糖", "consistency": "soft", "cost": 2.5},
    {"name": "牛奶硬糖", "consistency": "hard", "cost": 2.2},
    {"name": "酥心糖", "consistency": "crunchy", "cost": 3.0},
    {"name": "QQ糖", "consistency": "soft", "cost": 1.9}
]

# 统计总成本
total_costs = {}
for candy in candies:
    consistency = candy["consistency"]
    cost = candy["cost"]
    total_costs[consistency] = total_costs.get(consistency, 0) + cost

# 找最大值
highest_cost = max(total_costs.values())
highest_consistency = [k for k, v in total_costs.items() if v == highest_cost][0]

print("各类型糖果总成本:", total_costs)
print(f"总成本最高的是{highest_consistency},总计:{round(highest_cost, 2)}")

如果你的现有代码有特定问题(比如语法错误、逻辑漏洞),可以贴出来我帮你针对性修正~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:20:02