I have my solution for the below usecase but I would like to know whether is any other effective solution for the same.
My Data:
const myArr = [{
data: {
studyUId: 'abc',
seriesData: [ { seriesUId: "123", modality: "VX"}, { seriesUId: "ef3", modality: "GX"} ]
}
},
{
data: {
studyUId: 'fgh',
seriesData: [ { seriesUId: "grhg", modality: "VX"}, { seriesUId: "dter", modality: "GX"}, { seriesUId: "tg3", modality: "YX"} ]
}
},
{
data: {
studyUId: 'tyb',
seriesData: [ { seriesUId: "753", modality: "YX"}]
}
},
{
data: {
studyUId: 'fgh',
seriesData: [ { seriesUId: "grhg", modality: "VX"}, { seriesUId: "tg3", modality: "YX"} ]
}
}];
My Expected Outputs:
// All the values of `studyUId` without duplicates as an array
[ 'abc', 'fgh', 'tyb']
// All the values of `seriesUId` without duplicates as an array
[ '123', 'ef3', 'grhg', 'dter', 'tg3', '753']
My Solution:
const studyArr = [...new Set(myArr.map(el => el.data.studyUId ))];
console.log(studyArr);
const seriesArr = [...new Set(
myArr.map(el =>
el.data.seriesData.map(series => series.seriesUId)
).flat()
)];
console.log(seriesArr);
Although I have the solution, I am not sure whether it's the best way to do this!
Is there any better way to improve the solution to make it more efficient in terms of speed & code efficiency?
Any help would be appreciated.
array.flatMap()
on that second one. \$\endgroup\$