I have and array of objects, something like that:
myArr = [{id: 1, x:100, y:200},{id:1, x:50, y:25},{id:2, x:60, y:80},{id:2, x:50, y:100},{id:2, x:50, y:60}]
What I want is to make an array like that:
wantedArray = [{id: 1, x: 150, y: 225}, {id:2, x: 160, 240}]
Where make the addition of each x, y if "id" is the same. Thanks!
CodePudding user response:
You can use array#reduce
to sum on property x
and y
for each unique id
in an object accumulator.
const myArr = [{id: 1, x:100, y:200},{id:1, x:50, y:25},{id:2, x:60, y:80},{id:2, x:50, y:100},{id:2, x:50, y:60}],
result = Object.values(myArr.reduce((r, {id, x, y}) => {
r[id] = r[id] || {id, x: 0, y: 0};
r[id].x = x;
r[id].y = y;
return r;
},{}));
console.log(result);
CodePudding user response:
You do not need to reduce Object.values
This works too and saves a casting
const myArr = [{id: 1, x:100, y:200},{id:1, x:50, y:25},{id:2, x:60, y:80},{id:2, x:50, y:100},{id:2, x:50, y:60}]
const sum = myArr.reduce((acc,cur) => {
const obj = acc.find(({id}) => id===cur.id);
if (obj) { obj.x =cur.x; obj.y =cur.y }
else acc.push(cur)
return acc;
},[]);
console.log(sum)