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

JavaScript – Map over two object arrays, match key, and store key and property as array

I have two arrays:

Array 1:

['0000037_165', '0000037_62', '0000037_74', '0000037_165', ...]

Array 2:

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

[
 {SiteUniqueID: '0000037_165', Description: 'Description 1'},
 {SiteUniqueID: '0000037_165', Description: 'Description 2'},
 {SiteUniqueID: '0000037_62', Description: 'Description 1'},
 {SiteUniqueID: '0000037_74', Description: 'Description 1'},
 {SiteUniqueID: '0000037_165', Description: 'Description 1'},
 ...
]

I need to map over both arrays and check if the ‘SiteUniqueID’ from array 2 exists in array 1. If it exists in array 1 I then need to push the ID and the description into a new array.

As seen in Array 2, a Site ID may have more than one description.

So, the tricky part is that if the ID exists twice in array 2, then the description should be an array of all of the descriptions.

I have played around with a mixture of .map() and .find() with no luck so far.

I would like the resulting array to look like this:

[
 {SiteUniqueID: '0000037_165', Description: ['Description 1', 'Description2']},
 {SiteUniqueID: '0000037_62', Description: ['Description 1']},
 {SiteUniqueID: '0000037_74', Description: ['Description 1']},
 {SiteUniqueID: '0000037_165', Description: ['Description 1']},
  ...
]

Any help is appreciated!

>Solution :

Should also work:

var array1 = new Set(['0000037_165', '0000037_62', '0000037_74', '0000037_165'])

var array2 = [
    {SiteUniqueID: '0000037_165', Description: 'Description 1'},
    {SiteUniqueID: '0000037_165', Description: 'Description 2'},
    {SiteUniqueID: '0000037_62', Description: 'Description 1'},
    {SiteUniqueID: '0000037_74', Description: 'Description 1'},
    {SiteUniqueID: '0000037_165', Description: 'Description 1'}]

var newArray = [];

array1.forEach(x => {
    var results = array2.filter(y => y.SiteUniqueID === x);
    if (results?.length)
        newArray.push({SiteUniqueID: x, Description: results.map(z => z.Description)})
})

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