-4

I wanted to show only unique values in the div instead of all.

<div *ngFor="let user of allUser">
{{user.gender}}
</div>

But right now, it's populating all the values as per the screenshot

enter image description here

What changes do I need to do to show only unique values here? It should show 2 values as : Male and Female.

Kunal Vijan
  • 425
  • 2
  • 9
  • 28
  • 1
    You could use set that will remove your duplication – yazan Dec 22 '20 at 13:06
  • here's a good example on how you can filter your values to get only the unique ones: https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates – Vasile Rusu Dec 22 '20 at 13:07
  • @yazan will that be a filter something like `{{user.gender | unique }}` – Kunal Vijan Dec 22 '20 at 13:07
  • 1
    Please don't post relevant code/input/output as images. A good resource is [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – pilchard Dec 22 '20 at 13:12

2 Answers2

3

Create a getter in ts file(name could be anything).

get uniqueGenders(){
    return new Set(this.allUser.map(x=>x.gender))
}

and use it in template

<div *ngFor="let item of uniqueGenders">
  {{item}}
</div>

read more about getter and setter here

Nilesh Patel
  • 3,193
  • 6
  • 12
0

I guess they are stored in an array..? You can use the set (as mentioned by yazan)

let ngFor=['male', 'male', 'female', 'male', 'female']

let gender = [...new Set(ngFor)]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

Battleaxe
  • 64
  • 1
  • 7