gpt4 book ai didi

javascript - 如何使用 underscorejs 分组并获得平均值

转载 作者:行者123 更新时间:2023-11-29 19:10:40 25 4
gpt4 key购买 nike

如何使用下划线对category进行分组并取平均值?

我有一个对象数组。它应该按 category 分组,Analytics 的平均值是根据 val 属性计算的,即 1+2 => 3. 3/total类别数。所以,3/2 => 1.5

预期输出:{ Analytics: 1.5 }

[{
area:"Digital",
category:"Analytics",
qId:"wRHmpHHGzrYLsCEJ3",
type:"Reorganize",
userId:"M4JEJGiPZ8e9om9A",
val:1
},
{
area:"Digital",
category:"Analytics",
qId:"wRHmpHHGzrYLsCEJ3",
type:"Reorganize",
userId:"M4JEJGiPZ8e9om9A",
val:2
}]

谢谢

最佳答案

您可以 group the objects by category , 然后 iterate over all the keys in this resulting objectreduce the values :

var types = _.groupBy(array, 'category');
var result = _.mapObject(types, function(val, key) {
return _.reduce(val, function(memo, v) {
return memo + v.val;
}, 0) / val.length;
});

var array = [{
area:"Digital",
category:"Analytics",
qId:"wRHmpHHGzrYLsCEJ3",
type:"Reorganize",
userId:"M4JEJGiPZ8e9om9A",
val:1
},
{
area:"Digital",
category:"Analytics",
qId:"wRHmpHHGzrYLsCEJ3",
type:"Reorganize",
userId:"M4JEJGiPZ8e9om9A",
val:2
}];

var types = _.groupBy(array, 'category');
var result = _.mapObject(types, function(val, key) {
return _.reduce(val, function(memo, v) {
return memo + v.val;
}, 0) / val.length;
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

关于javascript - 如何使用 underscorejs 分组并获得平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39064019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com