I am trying to merge duplicate values if more than one same fields are exists in another object.
In below example - I have multiple objects of same asset_id and event_code which is repeated so I need to keep one and merge their value. I tried to do that but not getting the proper solution and output for the same.
const transaction = [{
value: 5,
asset_id: 'ABC',
event_code : 1
}, {
value: 15,
asset_id: 'HGF',
event_code : 1
}, {
value: 15,
asset_id: 'XYZ',
event_code : 2
}, {
value: 20,
asset_id: 'XYZ',
event_code : 2
}, {
value: 25,
asset_id: 'DEF',
event_code : 3
}, {
value: 20,
asset_id: 'HGF',
event_code : 3
}, {
value: 20,
asset_id: 'HGF',
event_code : 3
},
{
value: 10,
asset_id: 'ABC',
event_code : 1
}];
let newArr = [];
transaction.forEach(function (obj, ind, arr) {
if (ind === arr.length - 1 || obj.asset_id !== arr[ind + 1].asset_id && obj.event_code!== arr[ind + 1].event_code) {
newArr.push(obj);
} else {
arr[ind + 1].value+= obj.value;
}
});
console.log(newArr)
Expected Output Should be like this :
[{
value: 15,
asset_id: 'ABC',
event_code: 1
}, {
value: 15,
asset_id: 'HGF',
event_code: 1
}, {
value: 35,
asset_id: 'XYZ',
event_code: 2
} {
value: 25,
asset_id: 'DEF',
event_code: 3
}, {
value: 40,
asset_id: 'HGF',
event_code: 3
}]