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

Comparing two arrays, have one property from first to second where id of element is same

I’m learning javascript and want to work with two arrays by comparing them and do some merging of properties:

I have my array1 and array2 as :

array1 = [
          { id: 10, name: 'abc', otherData: 'other' },
          { id: 20, name: 'def', otherData: 'other' },
          { id: 30, name: 'ghi', otherData: 'other' },
        ];
array2 = [
          { id: 10, nameV2: 'xyz', otherData: 'other' },
          { id: 20, nameV2: 'pqr', otherData: 'other' },
          { id: 30, nameV2: 'tvs', otherData: 'other' },
        ];

I’m expecting this result where I will compare both arrays, iterate over elements, if id is same then have nameV2 key from array2 in array1's elements

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

expected output :

array1 = [
          { id: 10, name: 'abc', otherData: 'other', nameV2: 'xyz' },
          { id: 20, name: 'def', otherData: 'other', nameV2: 'pqr' },
          { id: 30, name: 'ghi', otherData: 'other', nameV2: 'tvs' },
        ];

how should I achieve this?

>Solution :

Here’s an approach to do this, we create a look-up map(idNameV2Map) using array2 and then use it to get the desired output

const array1 = [{ id: 10, name: 'abc', otherData: 'other' }, { id: 20, name: 'def', otherData: 'other' }, { id: 30, name: 'ghi', otherData: 'other' }];
const array2 = [{ id: 10, nameV2: 'xyz', otherData: 'other' }, { id: 20, nameV2: 'pqr', otherData: 'other' },{ id: 30, nameV2: 'tvs', otherData: 'other' }];

const idNameV2Map = array2.reduce((acc, curr) => {
   acc[curr.id] = curr.nameV2;
   return acc;
}, {});

const output = array1.map((item) => {
   if (idNameV2Map[item.id]) {
       return { ...item, nameV2: idNameV2Map[item.id] };
   }

   return item;
});

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