背景
我有以下数据集
let 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 }]}
]
我的要求是使它看起来像这样:
let animals =
[
{ animal:'cat',avg_score:3.5, avg_weight:26 },
{ animal:'dog',avg_score:5, avg_weight:24 }
]
其中 avg_score 和 avg_weight 应是相应标题的分数和权重的平均值。
阅读 loadash 的文档,我发现了这一点,
- 我们需要使用_.groupBy()函数按标题分组
- 我们需要使用 _mean() 函数来取平均值
我不知道如何一起完成这件事。到目前为止我尝试过的-
const answer = _( animals )
.groupBy( 'attributes.title' )
.map( () => ( {
title: attributes.title,
score: _.mean(attribute.score),
weight: _.mean(attribute.weight),
} ) )
.value();
console.log( "Master Data : " + answer );
但是,由于标题、分数和权重是子项,我们需要某种循环来迭代并获取相应行的实体,因此我无法进一步处理。例如,赋值应类似于 'title' : row.attributes.title
,其中 row 是来自循环的迭代的引用。
有人可以帮忙解开这个吗?
最佳答案
使用普通 ES6:
对于每个动物条目,使用reduce 来保存分数、体重和数量的运行总计。然后将平均值计算为总数/计数。
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 r = Object.values(animals.reduce((a,
{attributes:[{title,score,weight}]},o)=>(
o=(a[title]??={animal:title, count:0, totalScore:0, totalWeight:0}),
o.count++, o.totalScore+=score, o.totalWeight+=weight, a),{}))
.map(({animal,count,totalScore,totalWeight})=>
({animal, avg_score:totalScore/count, avg_weight:totalWeight/count}))
console.log(r)
关于javascript - 使用 Map、Sum、mean 使用 lodash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75552302/