简体   繁体   English

获取具有平均值的对象数组的重复计数

[英]Get repetition count of array of objects with average value

I Have a dataset that looks like this: 我有一个看起来像这样的数据集:

var arr = [
  { userid: "5bacc98431481e0520856df8", profitLoss: 401.4 },
  { userid: "5bacc98431481e0520856df8", profitLoss: -28.36 },
  { userid: "5bacc8c6563a882a1ca7756a", profitLoss: -26.14 },
  { userid: "5bacc8c6563a882a1ca7756a", profitLoss: 46.14},
  { userid: "5bacc8c6563a882a1ca7756a", profitLoss: 86.14}
];

Now I want the repetition count of userid with average value of profitLoss. 现在,我需要userid的重复计数和ProfitLoss的平均值。

Expected result will be like this:
var arr = [
  { userid: "5bacc98431481e0520856df8", profitLoss: 186.52, count: 2 },
  { userid: "5bacc8c6563a882a1ca7756a", profitLoss: 106.14, count: 3}
];

I know to get the repetition count of array but not on object; 我知道要获取数组的重复计数,而不是对象。 for repetition count of array the logic will be like this: 对于数组的重复计数,逻辑将如下所示:

var map = arr.reduce(function(prev, cur) {
  prev[cur] = (prev[cur] || 0) + 1;
  return prev;
}, {});

But I am confused on array of objects. 但是我对对象数组感到困惑。

You could take a Map and sum the values an count. 您可以制作一个Map并将这些值相加。 Later get the average. 以后得到平均值。

 var array = [{ userid: "5bacc98431481e0520856df8", profitLoss: 401.4 }, { userid: "5bacc98431481e0520856df8", profitLoss: -28.36 }, { userid: "5bacc8c6563a882a1ca7756a", profitLoss: -26.14 }, { userid: "5bacc8c6563a882a1ca7756a", profitLoss: 46.14 }, { userid: "5bacc8c6563a882a1ca7756a", profitLoss: 86.14 }], result = Array.from( array.reduce((m, { userid, profitLoss }) => { var temp = m.get(userid) || { sum: 0, count: 0 }; temp.sum += profitLoss; temp.count++; return m.set(userid, temp); }, new Map), ([userid, { sum, count }]) => ({ userid, average: sum / count, count }) ); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You could create dictionary with userid as key and object with sum and count. 您可以使用userid作为键创建字典,并使用sum和count创建对象。 Then it's enough to map entries to your result. 然后,将条目映射到您的结果就足够了。

 var arr = [ { userid: "5bacc98431481e0520856df8", profitLoss: 401.4 }, { userid: "5bacc98431481e0520856df8", profitLoss: -28.36 }, { userid: "5bacc8c6563a882a1ca7756a", profitLoss: -26.14 }, { userid: "5bacc8c6563a882a1ca7756a", profitLoss: 46.14}, { userid: "5bacc8c6563a882a1ca7756a", profitLoss: 86.14} ]; var userDict = arr.reduce((acc, el)=>{ if (!acc.hasOwnProperty(el.userid)){ acc[el.userid] = {sum: 0, count: 0} } acc[el.userid].sum += el.profitLoss; acc[el.userid].count++; return acc; }, {}); var result = Object.entries(userDict).map(([k,v])=>({userid: k, average: v.sum/v.count, count:v.count})); console.log(result) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM