javascript - 使用 Map、Sum、mean 使用 lodash

标签 javascript reactjs

背景

我有以下数据集

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 的文档,我发现了这一点,

  1. 我们需要使用_.groupBy()函数按标题分组
  2. 我们需要使用 _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/

相关文章:

javascript - 如何从包含该文本框文本的文本框 div 制作。是否可以?

javascript - 使用 localStorage 中的数据填充对象

javascript - 在 Android 浏览器中捕获浏览器关闭事件

reactjs - 预设文件不允许导出对象

node.js - React-typeahead - 不变违规 : addComponentAsRefTo(. ..) 问题

html - 在 HTML/CSS 中实现下拉列表

javascript - Reactjs,具有不同背景颜色的表格单元格

javascript - 准确检测浏览器是否支持平滑滚动?

javascript - 在 React 应用程序中将 Google Analytics 与到达路由器集成

javascript - wordpress主题中可点击的背景广告?