javascript - 如何计算 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"}
解决方案
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);
推荐阅读
- php - php中不以“/ap1/v1”开头的url模式的正则表达式如何
- java - WebView 读取和缩放图像不正确缩放
- mysql - 使用 SQL 从字段中的任意位置提取分隔的子字符串
- python - 我有两列数据需要比较。如果第 1 列中的值匹配,我需要添加它们对应的第 2 列值
- bluetooth - 解释 adafruit BLE 方法的标志以设置 GATT 特征
- javascript - Mongodb find 方法总是返回文档的所有元素
- javascript - 使用“connection”关键字连接到 Node JS websocket 的问题
- python - 设置 Huey 以将 Redis 与 Flask 一起使用
- angular - _co.addCourse() 不是一个函数——即使我已经在 ts 文件中定义了它
- numbers - 在easyphp devserver 17中更改端口号