Q:

Add/sum multiple values in array with same id

So lets say i have the following array. 
     [{idProduct:1, unitCost:400},
     {idProduct:1, unitCost:160},
     {idProduct:1, unitCost:46}, 
     {idProduct:2, unitCost:200},
     {idProduct:2, unitCost:40}

I cant seem to find the way to add the unit cost of product 1 and then cut off to add the other units cost of product 2 and so on... I actually want to append it to a different row in google spreadsheet but I first want to calculate it.
I tried some for/if loops but i always end up with the total cost for all products, not just individual ones.
This for gives out the total cost for all ids. When I palce an if inside this for, Im not sure how to compare the two ids, plus Im supposed to set totalCost back to 0 if i want to reset the sum
  for (var a = 0; a < arr.length ; a++) {
    totalCost= totalCost+ arr[a].unitCost;
  }

I tried an if with a break but that doesnt seem to work either, wanted to maybe try promises but Im not sure that would help. I also tried to set another for that compares the next ids to the one im currently in but that seemed to complicate things and the numbers i got were wrong.
I also tried
  for (var a = 0; a < arr.length ; a++) {
    if(arr[a].idProduct === arr[a+1].idProduct){
    totalCost= totalCost+ arr[a].unitCost;
    }
  }

But of course on the last id it compares it to undefinded since a+1 is longer than the length of the array.
Im honestly burned out by this by now, and im pretty sure its a simple solution, but I really dont know what else to do

A:

You can use reduce to summarize the array and add the values into an object using the idProduct as the key. Use Object.values to convert the object into an array.

let arr = [{"idProduct":1,"unitCost":400},{"idProduct":1,"unitCost":160},{"idProduct":1,"unitCost":46},{"idProduct":2,"unitCost":200},{"idProduct":2,"unitCost":40}]

let result = Object.values(arr.reduce((c, {idProduct,unitCost}) => {
  c[idProduct] = c[idProduct] || {idProduct,unitCost: 0};
  c[idProduct].unitCost += unitCost;
  return c;
}, {}));

console.log( result );

Or you can use the idProduct as the key like and the sum as the value like:

let arr = [{"idProduct":1,"unitCost":400},{"idProduct":1,"unitCost":160},{"idProduct":1,"unitCost":46},{"idProduct":2,"unitCost":200},{"idProduct":2,"unitCost":40}]

let result = arr.reduce((c, {idProduct,unitCost}) => {
  c[idProduct] = c[idProduct] || 0;
  c[idProduct] += unitCost;
  return c;
}, {});

console.log(result);

