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

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

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