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

时间:2018-11-06 07:38:24

标签: javascript

我有一个像这样的数据集:

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}
];

现在,我希望用户ID的重复计数为profitLoss的平均值。

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

我知道要获取数组的重复计数,而不是对象。 对于数组的重复计数,逻辑将是这样的:

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

但是我对对象数组感到困惑。

2 个答案:

答案 0 :(得分:0)

您可以使用Map并将这些值相加。稍后获得平均值。

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; }

答案 1 :(得分:0)

您可以创建以userid为键的字典,并创建具有sum和count的对象。然后,将条目映射到您的结果就足够了。

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)