0

I have a Filter in my Angular-Project that loads data from Firebase.

Current status in Filter:

  • Name 1: Lea Muster
  • Name 2: Bruno Mustermann
  • Name 3: Lea Muster
  • Name 4: Gabriela Musterfrau

Goal: Lea Muster is a duplicate in the data but should be displayed only once in the filter.

  • Name 1: Lea Muster
  • Name 2: Bruno Mustermann
  • Name 4: Gabriela Musterfrau

How can I display only unique values?

Component.ts-File

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { AngularFirestore } from '@angular/fire/firestore';

export interface Profile {
  topic: string;
  location: string;
  gender: string;
}

interface Gender {
  value: string;
  viewValue: string;
}

@Component({
  selector: 'app-filtermain',
  templateUrl: './filtermain.component.html',
  styleUrls: ['./filtermain.component.css'],
})
export class FiltermainComponent implements OnInit {
  people: Gender[] = [
    { value: 'mann-0', viewValue: 'Mann' },
    { value: 'frau-1', viewValue: 'Frau' },
    { value: 'norole-2', viewValue: 'Spielt mir keine Rolle' },
  ];
  profile: Profile[] | undefined;

  therapykind = new FormControl();

  therapyplace = new FormControl();

  constructor(private afs: AngularFirestore) {}

  ngOnInit(): void {
    console.log('Init');
    this.afs
      .collection<Profile>('profiles')
      .valueChanges()
      .subscribe((values: any) => {
        console.log(values);
        this.profile = values;
      });
  }
}

Component.html-File

<div>
  <h2>Wo möchtest du deine Therapie machen?</h2>
  <mat-form-field appearance="fill">
    <mat-label>Wähle deinen Lieblingsort</mat-label>
    <mat-select [formControl]="therapyplace" multiple>
      <mat-option *ngFor="let profile of profile">
        {{ profile.location }}</mat-option
      >
    </mat-select>
  </mat-form-field>
</div>

I tried already a pipe but then only errors evolved.

Many thanks

user14858919
  • 33
  • 1
  • 4

1 Answers1

1

Try this - First Make a new function that will return new unique array.

getUniqueArray() {
    const key = 'Name';  //use the key that contains the duplicate values.
    newArray = [...new Map(this.profile.map(item =>
    [item[key], item])).values()];
    return newArray ;   //This newArray will have unique values.
}

Then call this function in your code like this.

ngOnInit(): void {
  this.afs
  .collection<Profile>('profiles').valueChanges().subscribe((values: any) => {
    this.profile = values;
    this.profile = this.getUniqueArray();    
  });
}

I hope that will be helpful for you.