3
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Not much to improve other than to use array.flatMap() on that second one. \$\endgroup\$ Commented May 10, 2023 at 13:23
  • \$\begingroup\$ Thank you @Joseph \$\endgroup\$ Commented May 10, 2023 at 13:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.