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 do I make deduped array from object property?

I am looking for a way to loop over an array of objects and make a new array from the contents of an object property. See the array below. I want to make an array called topics (with no duplicates) from each of the topic properties on each object.

const data = [
  {
    topics [
      "tutorial",
      "JS",
      "Video"
    ],
    ...
  },
  {
    topics [
      "tutorial",
      "CSS",
      "Testing"
    ],
    ...
  },
  {
    topics [
      "HTML",
      "JS",
      "Music"
    ],
    ...
  }
]

I was thinking of:

let topics = []

data.forEach((item) => {
  topics.push(item.topics, ...topics)
})

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

>Solution :

You need to use flatMap method to flat the topics together, and with new Set(Array) you will get the unique values.

const data = [
  {
    topics:  [
      "tutorial",
      "JS",
      "Video"
    ],
  },
  {
    topics: [
      "tutorial",
      "CSS",
      "Testing"
    ],
  },
  {
    topics: [
      "HTML",
      "JS",
      "Music"
    ],
  }
]

const topics = new Set(data.flatMap(item => item.topics))

console.log(Array.from(topics))
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