首页 > 解决方案 > 如何计算 ID 相同的平均值,然后删除该 ID 的重复项,但保留在 javascript 中具有平均值的 ID

问题描述

我有一个像下面这样的对象

{id: "1", score:"2"}
{id: "1", score:"2"}
{id: "1", score:"2"}
{id: "3", score:"3"}
{id: "3", score:"2"}
{id: "3", score:"3"}
{id: "9", score:"4"}
{id: "9", score:"4"}
{id: "9", score:"4"}

并期待如下输出

{id: "1", score:"2"}
{id: "3", score:"2.6"}
{id: "9", score:"4"}

标签: javascriptjquery

解决方案


您可以使用mapreduce轻松实现此目的。

1)

const arr = [
  { id: "1", score: 2 },
  { id: "1", score: 2 },
  { id: "1", score: 2 },
  { id: "3", score: 3 },
  { id: "3", score: 2 },
  { id: "3", score: 3 },
  { id: "9", score: 4 },
  { id: "9", score: 4 },
  { id: "9", score: 4 },
];

const result = arr
  .reduce((acc, { id, score }) => {
    const obj = acc.find((el) => el.id === id);
    if (!obj) acc.push({ id, score: [score] });
    else {
      obj.score.push(score);
    }
    return acc;
  }, [])
  .map(({ id, score }) => {
    const total = score.reduce((acc, curr) => acc + curr, 0) / score.length;
    return { id, score: total };
  });
  
  console.log(result);

2)

const arr = [
  { id: "1", score: 2 },
  { id: "1", score: 2 },
  { id: "1", score: 2 },
  { id: "3", score: 3 },
  { id: "3", score: 2 },
  { id: "3", score: 3 },
  { id: "9", score: 4 },
  { id: "9", score: 4 },
  { id: "9", score: 4 },
];

const result = arr
  .reduce((acc, { id, score }) => {
    const obj = acc.find((el) => el.id === id);
    if (!obj) acc.push({ id, score, len: 1 });
    else {
      obj.score += score;
      ++obj.len;
    }
    return acc;
  }, [])
  .map(({ id, score, len }) => ({ id, score: score / len }));

console.log(result);


推荐阅读