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

Merge duplicates in array of objects while adding up specific field

I have an array of objects as follow :

const array = [
    {poleId: 1, jobCount: 1},
    {poleId: 1, jobCount: 2},
    {poleId: 5, jobCount: 8},
    {poleId: 7, jobCount: 1},
    {poleId: 2, jobCount: 10},
    {poleId: 2, jobCount: 3},
]

I’d like to "merge" the duplicate objects having the same poleId while adding up their jobCount, to get a result of this sort :

const result = [
    {poleId: 1, jobCount: 3},
    {poleId: 5, jobCount: 8},
    {poleId: 7, jobCount: 1},
    {poleId: 2, jobCount: 13},
]

I can’t figure out any clean way to do this.

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

Thanks in advance!

>Solution :

Try some thing like below. Build an object with keys as poleId and value as jobCount (combine jobCount when key is same)

const process = (arr, output = {}) => {
  arr.forEach(({ poleId, jobCount }) => {
    output[poleId] = {
      poleId,
      jobCount: (poleId in output ? output[poleId].jobCount : 0) + jobCount,
    };
  });
  return Object.values(output);
};

const array = [
  { poleId: 1, jobCount: 1 },
  { poleId: 1, jobCount: 2 },
  { poleId: 5, jobCount: 8 },
  { poleId: 7, jobCount: 1 },
  { poleId: 2, jobCount: 10 },
  { poleId: 2, jobCount: 3 },
];

console.log(process(array));
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