[英]How to calculate average where ID is same and then remove duplicates of that ID but keep the one which has average in javascript
我有一个 object 如下所示
{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"}
并期待像下面这样的 output
{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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.