Sum values with the same key

I’m trying to add two values for the same id.
This can be dynamic but here is a simple example;
{
id=ABC123,
Value=100
},
{
id=ABC123,
Value=200
},
{
id=XYZ123,
Value=100
}

Here I want to get sum of Value for id=ABC123 equals 300.
Basically look through the items where “id” match and there sum “Value”

Thank you for your help!

I tried something like this but couldn’t get it to work:

let obj = [items.json]

var holder = {};

obj.forEach(function(d) {
if (holder.hasOwnProperty(d.id)) {
holder[d.ACCOUNT_ID] = holder[d.id] + d.Value;
} else {
holder[d.id] = d.value;
}
});

var obj2 = [];

for (var prop in holder) {
obj2.push({ id: prop, value: holder[prop] });
}

return [{json: {obj2}}];

found a solution:

let data = $items(“IF”)

console.log(data);

const result2 = items.map((el, index, array) => {
if (array[index + 1] && el.json.id === array[index + 1].json.id) {
return {
…el.json,
Value: array[index + 1].json.Value + el.json.Value
}
}

return {
    ...el.json
};

})

console.log(result2);
return [{json: {result2}}];

1 Like

Sweet, thanks so much for confirming and for sharing your approach!

1 Like

I have something similar but cannot figure out the code.
Can someone help?

I need to sum all the “Sold” - “Refund”

Hi @kgurinov, try this approach:

This will produce a result like so:

ok, how to do the Sold - Refund = Quantity?

Oh, I didn’t get that you wanted to calculate a third field. You could simply add the field before pushing the result using result['Quantity'] = result['Sold'] - result['Refund'], in a workflow this would look like so:

I should say that this isn’t really n8n logic, so it might be worth learning a bit of JavaScript in order to be able to write such functions going forward.

1 Like

I’ve seen this a few times on the community and understand the need to do some easy math.
Sooooooo,
Math community node comming soon :innocent:

3 Likes