如何在数组中分组类别数组

时间:2016-08-21 14:31:30

标签: underscore.js

如何从 答案 属性中分组数组 数组 并使用下划线获取平均值?< / p>

我有嵌套的对象数组。它应按类别分组,并根据val属性计算Analytics的平均值,即1 + 2 =&gt; 3. 3 /类别总数。所以,3/2 =&gt; 1.5

预期输出:{Analytics:1.5}

[ 
{ _id:"oq8DRjm6uA9mtoJvw", 
answers:[
{
  area:"Digital",
  category:"Analytics",
  qId:"wRHmpHHGzrYLsCEJ3",
  type:"Reorganize",
  userId:"M4JEJGiPZ8e9om9A",
  val:1
},
{
  area:"Digital",
  category:"Analytics",
  qId:"wRHmpHHGzrYLsCEJ3",
  type:"Reorganize",
  userId:"M4JEJGiPZ8e9om9A",
  val:2
}
],
date:Tue Aug 16 2016 11:13:59
}]

由于

2 个答案:

答案 0 :(得分:1)

如果我理解你的问题是正确的...... 最简单的解决方案是迭代数组并为您检查的每个元素填充另一个数组。

数组应包含

{
categoryName: '',
valueSum: 0,
count: 0
}

O(n ^ 2)复杂度的算法如下:

  • 获取数组的下一个元素
  • 如果临时数组中存在类别,请将当前值添加到 valueSum 并增加计数
  • 如果类别不存在,请使用类别,值并将计数设置为1
  • 将元素添加到数组中

当您迭代整个数组时,开始迭代临时数组并除以 valueSum / 计数,这将为您提供AVG的每个类别。

答案 1 :(得分:1)

如果你只想要数组中第一个对象的平均答案,你可以得到答案数组,group the objects by categoryiterate over all the keys in this resulting object,以及reduce the values

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

var array = [{ 
  _id:"oq8DRjm6uA9mtoJvw", 
  answers: [
  {
    area:"Digital",
    category:"Analytics",
    qId:"wRHmpHHGzrYLsCEJ3",
    type:"Reorganize",
    userId:"M4JEJGiPZ8e9om9A",
    val:1
  },
  {
    area:"Digital",
    category:"Analytics",
    qId:"wRHmpHHGzrYLsCEJ3",
    type:"Reorganize",
    userId:"M4JEJGiPZ8e9om9A",
    val:2
  }],
  date: 'Tue Aug 16 2016 11:13:59'
}];

var answers = array[0].answers;
var types = _.groupBy(answers, '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>