Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find similar value of an array object and calculate the sold

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

output sold : 12

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading