Seeking for help in a JavaScript problem. I am new to Nodejs, JavaScript. I am trying to merge duplicate values in the array if exists.
In below example - I have multiple asset_id which is repeated so I need to keep one and merge their values. I tried to do that but not getting the proper solution and output for the same.
const transaction = [{
total_duration: 5,
asset_id: 'ABC',
}, {
total_duration: 15,
asset_id: 'HGF',
}, {
total_duration: 15,
asset_id: 'XYZ',
}, {
total_duration: 20,
asset_id: 'XYZ',
}, {
total_duration: 25,
asset_id: 'DEF',
}, {
total_duration: 20,
asset_id: 'HGF',
}, {
total_duration: 20,
asset_id: 'HGF',
},
{
total_duration: 10,
asset_id: 'ABC',
}];
let newArr = [];
transaction.forEach(function (obj, ind, arr) {
if (ind === arr.length - 1 || obj.asset_id !== arr[ind + 1].asset_id) {
newArr.push(obj);
} else {
arr[ind + 1].total_duration += obj.total_duration;
}
});
console.log(newArr)