【问题标题】:Working with Map, Sum, mean using loadash使用 Map、Sum,均值使用 lodash
【发布时间】:2023-02-24 11:38:18
【问题描述】:

背景

我有以下数据集

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,其中行是来自循环的迭代的引用。 有人可以帮忙展开这个吗?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    使用普通 ES6:

    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 }]}]
    
    console.log(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})))

    【讨论】:

      猜你喜欢
      • 2023-02-05
      • 2022-01-12
      • 2012-04-17
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多