Home > Blockchain >  How do I make deduped array from object property?
How do I make deduped array from object property?

Time:08-04

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)
})

CodePudding user response:

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))

  • Related