Merge 2-D array of objects based on common key

I have a 2-D array as below :

[
  [ 
    { basecount: 343, campaign_name: '1.Stay_Connected_Plus:SP_JCA' },
    { basecount: 342, campaign_name: '1.Stay_Connected_Plus:JP_JCA' }
  ],
  [ 
    { basecount: 102, campaign_name: '1.Stay_Connected_Plus:SP_JCA' },
    { basecount: 102, campaign_name: '1.Stay_Connected_Plus:PP_JCA' }   
  ]
]

I want it to be formatted as below :

[ 
  { basecount: 445, campaign_name: '1.Stay_Connected_Plus:SP_JCA' },
  { basecount: 342, campaign_name: '1.Stay_Connected_Plus:JP_JCA' },
  { basecount: 102, campaign_name: '1.Stay_Connected_Plus:PP_JCA' }     
]

Basically, we need do the sum of basecount if the campaign_name is common, otherwise just keept it as it is.

I am able to achieve my purpose through iterating the 2-D arrays, checking the campaign_name and doing the sum of basecount if it matches. I want to know if there is any other optimized way to do this

Thanks in advance.

>Solution :

You can flatten the array, then use Array#reduce with an object to store the values for each name.

let arr=[[{basecount:343,campaign_name:"1.Stay_Connected_Plus:SP_JCA"},{basecount:342,campaign_name:"1.Stay_Connected_Plus:JP_JCA"}],[{basecount:102,campaign_name:"1.Stay_Connected_Plus:SP_JCA"},{basecount:102,campaign_name:"1.Stay_Connected_Plus:PP_JCA"}]];
let res = Object.values(arr.flat().reduce((acc, {basecount, campaign_name}) => {
  (acc[campaign_name] ??= {campaign_name, basecount: 0}).basecount += basecount;
  return acc;
}, {}));
console.log(res);

Leave a Reply