I saw this snippet online that have the same scenario as my problem. I want to understand this code. Can anyone please enlighten me how the row which says " res[value.Id].qty += value.qty;" changes the value of the already inserted item in result array.
I am talking about line 14 in this jsfiddle snippet https://jsfiddle.net/1xuamw9f/4/
Line 14 changes the value of the code in Line 12. How does that work?
var array = [
{ Id: "001", qty: 1 },
{ Id: "002", qty: 2 },
{ Id: "001", qty: 2 },
{ Id: "003", qty: 4 }
];
var result = [];
var x = array.reduce(function(res, value) {
if (!res[value.Id]) {
res[value.Id] = { Id: value.Id, qty: 0 };
result.push(res[value.Id])
}
res[value.Id].qty += value.qty;
return res;
}, {});
console.log(result)
console.log(x)