I have two arrays:
Array 1:
['0000037_165', '0000037_62', '0000037_74', '0000037_165', ...]
Array 2:
[
{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!
CodePudding user response:
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);
CodePudding user response:
Check this code out.
let arr1 = ['0000037_165', '0000037_62', '0000037_74', '0000037_165'];
let arr2 = [{
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'
},
]
let arrMod = [];
arr2.forEach(a => {
if (arr1.includes(a.SiteUniqueID)) {
let index = arrMod.findIndex(arrMod => arrMod.SiteUniqueID === a.SiteUniqueID);
if (index !== -1) {
arrMod[index].Description.push(a.Description);
} else {
arrMod.push({
SiteUniqueID: a.SiteUniqueID,
Description: [a.Description]
});
}
}
});
console.log(arrMod);