0

Hi I have a JavaScript array, which looks something like the following.

{x: red, y: 2}
{x: blue, y: 3}
{x: blue, y; 4}
{x: green, y: 5}

My question is, how to add up the dupilicates, so in the end my array looks like the code below.

Also could the process be done in a loop since I actually have a much larger amount of data to format this way.

{x: red, y: 2}
{x: blue, y: 7} #the two blue y variables have been added
{x: green, y: 5}
sppokky
  • 115
  • 6
  • Alternative duplicate: [How to group by and sum an array of objects?](https://stackoverflow.com/questions/29364262/how-to-group-by-and-sum-an-array-of-objects) – Ivar Jul 15 '21 at 16:38

1 Answers1

0

Try:

var xs = [];

const data=[{x:"red",y:2},{x:"blue",y:3},{x:"blue",y:4},{x:"green",y:5}];

var n = []
data.forEach((e) => {
  if (!xs.includes(e.x)) { n.push(e); xs.push(e.x) }
  else { n.forEach(f => f.y += f.x == e.x ? e.y : 0) }
})

console.log(n);
Spectric
  • 30,714
  • 6
  • 20
  • 43