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.
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));