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

使用Lodash实现动物数据按类型分组并计算评分与权重平均值

解决方案

首先看你的数据集,每个动物的attributes是一个只包含单个对象的数组,处理时需要先获取这个数组里的唯一元素。下面是用Lodash实现需求的正确代码:

const animals = [
  {id:1, attributes:[{ title:'cat',score:3, weight:30 }]},
  {id:2, attributes:[{ title:'cat',score:4, weight:22 }]},
  {id:3, attributes:[{ title:'dog',score:5, weight:26 }]},
  {id:4, attributes:[{ title:'dog',score:5, weight:22 }]}
];

const answer = _(animals)
  // 按attributes数组中第一个对象的title分组
  .groupBy(item => item.attributes[0].title)
  // 遍历每个分组,计算平均值并构造目标对象
  .map((group, animalType) => ({
    animal: animalType,
    avg_score: _.mean(group, item => item.attributes[0].score),
    avg_weight: _.mean(group, item => item.attributes[0].weight)
  }))
  .value();

console.log(answer);

原代码的问题说明:

  • groupBy('attributes.title')无法正确获取分组键:因为attributes是数组,Lodash的字符串路径无法直接穿透数组取到内部对象的title,必须用自定义函数明确取出attributes[0].title。
  • map函数没有接收正确参数:你的map回调里没有获取到分组后的数组和分组键,无法遍历计算平均值。
  • 平均值计算未正确嵌套取值:需要从每个动物的attributes[0]里取出score和weight,再传入_.mean。

运行上述代码后,会得到你需要的结果:

[
  { animal: 'cat', avg_score: 3.5, avg_weight: 26 },
  { animal: 'dog', avg_score: 5, avg_weight: 24 }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:48:24