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 unique values from a list of objects?

Data:

[
  {
    "name": "Ankh of Anubis",
    "rank": {
      "_type": "medal",
      "current": "ankh-of-anubis"
    }
  },
  {
    "name": "Bonus Roulette",
    "rank": {
      "_type": "medal",
      "current": "bonus-roulette"
    }
  },
  {
    "name": "jetx",
    "rank": {
      "_type": "medal",
      "current": "jetx"
    }
  },
  {
    "name": "Gates of Olympus",
    "rank": {
      "_type": "trophy",
      "current": "gates-of-olympus"
    }
  },
]

How to filter only unique values,

uniqueValues = ["medal","trophy"]

I tried,

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

  1. const uniqueTitles = new Set(games.category.title);
  2. const uniqueTitles = [...new Set(games.category.title)] //typescript error.
 useEffect(() => {
    const uniqueTitles = games.filter((game:any) => {
      return new Set(game.category.title);
    })
    setTitles(uniqueTitles);
  },[])

>Solution :

You are using Set as the return value for a filter function. Is it really intended that way?
Given the data:

const data = [
  {
    "name": "Ankh of Anubis",
    "rank": {
      "_type": "medal",
      "current": "ankh-of-anubis"
    }
  },
  {
    "name": "Bonus Roulette",
    "rank": {
      "_type": "medal",
      "current": "bonus-roulette"
    }
  },
  {
    "name": "jetx",
    "rank": {
      "_type": "medal",
      "current": "jetx"
    }
  },
  {
    "name": "Gates of Olympus",
    "rank": {
      "_type": "trophy",
      "current": "gates-of-olympus"
    }
  },
]

You can do this:

const uniqueValues = new Set();
data.forEach(record => uniqueValues.add(record.rank._type));
console.log(uniqueValues);

Here’s the link.

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