In my JavaScript code, I have an object called obj
. I am trying to figure out how to remove duplicates in the info
array and calculate the sum of the quantities (qty
) for each unique key. Can you help me with this problem?
function updateTotalQuantity(obj) {
return obj.map(item => ({
...item,
total: item.info.reduce((acc, curr) => acc + curr.qty, 0)
}));
}
var obj = [
{id:1, info:[{idx:1, qty: 1}, {idx:2, qty: 2},{idx:2, qty: 2}], code: "sample1", total: 1},
{id:2, info:[{idx:3, qty: 2}, {idx:4, qty: 2}], code: "sample2", total: 2}
]
Desired Result:
[
{id:1, info:[{idx:1, qty: 1}, {idx:2, qty: 2}], code: "sample1", total: 3},
{id:2, info:[{idx:3, qty: 2}, {idx:4, qty: 2}], code: "sample2", total: 4}
]