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

How to get distinct value from an array of objects containing array

I am trying to get an array of distinct values from the data structure below. I tried using reduce and object keys with no luck. Can somebody please point me in the right direction?

Data:

var data = [{
    "id": 1,
    "Technologies": ["SharePoint", "PowerApps"]
  },
  {
    "id": 2,
    "Technologies": ["SharePoint", "PowerApps", "SomethingElse"]
  },
  {
    "id": 3,
    "Technologies": ["SharePoint"]
  },
  {
    "id": 4,
    "Technologies": ["PowerApps"]
  },
  {
    "id": 5,
    "Technologies": null
  }
]

Finished result should look like:

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

var distintValues = ["PowerApps", "SharePoint", "SomethingElse", null]

My attempt:
https://codepen.io/bkdigital/pen/MWEoLXv?editors=0012

>Solution :

You could use .flatMap() with a Set. .flatMap allows you to map each object’s technology to one resulting array, and the Set allows you to remove the duplicates. With the help of optional chaining ?., you can also keep the null value (so it doesn’t throw when accessing Technologies) like so:

const data = [{ "id": 1, "Technologies": ["SharePoint", "PowerApps"] }, { "id": 2, "Technologies": ["SharePoint", "PowerApps", "SomethingElse"] }, { "id": 3, "Technologies": ["SharePoint"] }, { "id": 4, "Technologies": ["PowerApps"] }, { "id": 5, "Technologies": null } ];

const res = [...new Set(data.flatMap(obj => obj?.Technologies))];
console.log(res);
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