Hi am trying to find similar value of this array object and calculate the some of sold for each same values
const sold = [
{ matri: 1, year: 2019, sold: 5 },
{ matri: 2, year: 2020, sold: 3 },
{ matri: 1, year: 2020, sold: 7 },
];
above i have one array object the expected output
{ matri: 1, year: 2020, sold: 5 },
{ matri: 1, year: 2020, sold: 7 },
sold: 5 sold: 7
output sold : 12
CodePudding user response:
You can use reduce
to group and sum the sold
property:
const sold = [
{ matri: 1, year: 2019, sold: 5 },
{ matri: 2, year: 2020, sold: 3 },
{ matri: 1, year: 2020, sold: 7 },
];
const result = Object.values(sold.reduce((carry, entry) => {
if (!carry.hasOwnProperty(entry.matri)) {
carry[entry.matri] = {matri: entry.matri, sold: entry.sold};
}
else {
carry[entry.matri].sold = entry.sold;
}
return carry;
}, {}));
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>